bind the click event to all links in a div with a certain class name - asp.net-mvc

The first parts of the jquery call inside the document.ready is pseudo code. How can I do the $('.mainLink').each().click() correctly so that all links with class name mainLinks inside the NavigationPanel are bound to the click event. Is it bad to not use an id for a link?
$(document).ready(function () {
$('.mainLink').each().click(function (e) {
e.preventDefault();
$.ajax({
url: this.href,
beforeSend: OnBegin,
complete: OnComplete,
success: function (html) {
$('#ContentPanel').html(html);
}
});
});
});
<div id="NavigationPanel">
#Html.ActionLink("1", "Index", "First", null, new { #class = "mainLink" })
#Html.ActionLink("2", "Index", "Two", null, new { #class = "mainLink" })
#Html.ActionLink("3", "Index", "Three", null, new { #class = "mainLink" })
</div>

Just do $('.mainLink').click(function (e) { which should bind all links with class .mainLink
If you want all links inside div ID NavigationPanel then try below,
$('.mainLink', $('#NavigationPanel')).click(function (e) {

If you just want to bind to all .mainLink within #NavigationPanel, the following works:
$("#NavigationPanel").on("click", ".mainLink", function(e){
e.preventDefault();
$.ajax({
url: this.href,
beforeSend: OnBegin,
complete: OnComplete,
success: function (html) {
$('#ContentPanel').html(html);
}
});
});

Related

Dynamically added form ajax not work

I have a list of div's.
When I click on a button in a div I switch div content with partial view which contain form.
This is code that happens when I click on that button:
#Html.ActionLink("edit", "EditUserLanguage", "UserLanguage", new { userLanguageId = Model.UserLanguageId }, new { #class = "editButton" })
...
$(document).on('click', '.editButton', function (e) {
$.ajax({
url: this.href,
cache: false,
success: function (html) {
var id = $(e.target).closest("div").attr("id");
$("#" + id).empty();
$("#" + id).append(html);
}
});
return false;
});
Html (partial view) that I add has:
#using (Html.BeginForm("UpdateUserLanguage", "UserLanguage", FormMethod.Post, new { id = "updateUserLanagegeForm" }))
{
...
This main view where is the list of div's and where I add this new partial view I have this code:
$(function () {
$('#updateUserLanagegeForm').submit(function () {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
alert("work");
}
});
return false;
});
}); //update
When I click on submit action method is invoked and I get new partial view returned but not via ajax.
I only get that partial view returned. alert("work"); is never called.
What could be the reason that this ajax call doesn't work?
submit handler is not being attached to form as form gets loaded after dom ready. So change your code to -
$('body').on('submit','#updateUserLanagegeForm',(function () {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
alert("work");
}
});
return false;
});
This will attach handler to form even if it is added dynamically.

How to open Edit popup using JqueryUi popup on mvc 3 Grid?

Hi; i have a problem. i want to open a popup(Jqueryui popup) on webpage. But i can not. How to make it correctly?
View:
grid.Column("", format: (item) => Html.ActionLink("Click", "", "", new { #customerId = ConvertUtil.ToInt(item.Id) }, new { #class = "popupLink" })),
OR
grid.Column("", format: (item) => Html.ActionLink("Click", "Edit", "Customer", new { #customerId = ConvertUtil.ToInt(item.Id) }, new { #class = "popupLink" })),
Jquery Code:
$(".popupLink").click(function () {
jQuery('#dialog').dialog('open');
});
Controller
public ActionResult Edit()
{
return View();
}
i need also id value. Not only popup. i wan to open Edit Pop up. How to open edit popup any row?
First of all, you need to stop default action of the click event
$(".popupLink").click(function (e) {
$('#dialog').dialog('open');
e.preventDefault();
});
That will show empty dialog (of course if you have #dialog container in your view).
Before showing the dialog you must load proper view. I would do this like that:
var url = $(this).attr('href');
$('#dialog').load(url);
Finally, the whole solution:
$(".popupLink").click(function (e) {
$('#dialog').load($(this).attr('href'));
$('#dialog').dialog('open');
e.preventDefault();
});
The following solution can be reused on an ActionLink without modifying the source document. It also won't show the dialog until the loading is complete:
$("a.popuplink").live("click", function (evt) {
evt.preventDefault();
$("<div></div>").insertAfter(this);
$.ajax({
url: this.href,
context: this
}).done(function (data) {
$(this).next('div').html(data);
$(this).next('div').dialog();
});
});

Replace the Ajax.ActionLink by the same functionality with jQuery

With asp.net mvc we can do an ajax call like this:
#{
var ajaxOpts = new AjaxOptions { UpdateTargetId = "main-content", OnBegin = "fctTabLoading", OnComplete = "fctTabLoaded", InsertionMode = InsertionMode.Replace };
}
#Ajax.ActionLink("my link text", "MyAction", "MyController", new { id = Model.RequestID }, ajaxOpts)
Which produce the following html:
<a data-ajax="true" data-ajax-begin="fctTabLoading" data-ajax-complete="fctTabLoaded" data-ajax-mode="replace" data-ajax-update="#main-content" href="/MyController/MyAction/19">my link text</a>
Now I would like to execute the same ajax call but from jQuery and I don't know how to proceed!
I would like something like:
$.ajax({
type: "Post",
url: myURL,
begin: fctTabLoading,
complete: fctTabLoaded,
mode: "replace",
update: "#main-content",
cache: false,
success: function () { alert('success'); }
});
I know the above ajax script won't work because 'mode' and 'update' are not recognized. So I am blocked.
It drives me crazy :(
Why I cannot use the MVC ActionLink? Because I first need to show a jquery dialog to let the user confirm then only do the ajax call in order to refresh a specific div on my page.
Any help is greatly appreciated.
Thanks.
You could start by replacing your Ajax link with a normal link:
#Html.ActionLink(
"my link text", // linkText
"MyAction", // actionName
"MyController", // controllerName
new { id = Model.RequestID }, // routeValues
new { id = "mylink" } // htmlAttributes
)
which will produce the following markup:
my link text
and then in a separate js file unobtrusively AJAXify it:
$(function() {
$('#mylink').click(function() {
$.ajax({
url: this.href,
type: 'POST',
beforeSend: fctTabLoading, // corresponds to your OnBegin callback
complete: fctTabLoaded, // corresponds to your OnComplete callback
success: function(result) {
$('#main-content').html(result);
}
});
return false;
});
});
As you know, the Ajax.ActionLink uses jquery.unobtrusive-ajax.js to execute the ajax links.
If you look at that file, you will see that the event handlers use jquery's live event binder. This binds the event listener to the document object. So, if you wanted to confirm before this event was triggered, you could bind directly to the element like the following:
$('#YOUR_ELEMENT').click(function () {
var confirmed = confirm("CONFIRM_MESSAGE");
if (!confirmed ) {
return false;
}
return true;
});
To use jquery dialog you could do the following:
function confirmDialog () {
$('#YOUR_DIALOG').dialog(
{ buttons: { "Ok": function() { return true; },
{ "Cancel": function() {return false;}
}
});
}
and then you would set confirmed in the previous function to confirmDialog().
***The dialog options may not be exactly what you want, but this should get you going.

ASP.NET MVC 3 + jQuery Ajax JSON - Prevent JSON from opening in new page

I have an Action Method that returns a JSON-serialized object. The problem I'm having is that the JSON returned is opening in a new page, instead of being processed by the "success" function of the jquery.Ajax method.
Here's the controller action:
[HttpPost]
public ActionResult AddAssignment(AssignmentViewModel avm)
{
db.Assignments.Add(new Assignment
{
Name = avm.Name,
DueDate = DateTime.Parse(avm.DueDate),
CourseID = avm.CourseID,
IsComplete = false
});
db.SaveChanges();
avm.Course = db.Courses
.Where(x => x.CourseID == avm.CourseID)
.SingleOrDefault()
.Name;
return Json(avm);
}
Here's the View (form):
#model Fooburg.Mvc.Models.AssignmentViewModel
<h2 style="margin: 0 0 24px 0">Add Assignment:</h2>
#using (Html.BeginForm("AddAssignment",
"Assignments",
FormMethod.Post,
new { #id = "add-assignment-form" }))
{
<dl class="tabular">
<dt>Course:</dt>
<dd>
#Html.DropDownListFor(x => x.CourseID, new SelectList(ViewBag.Courses, "CourseID", "Name"))
</dd>
<dt>Assignment:</dt>
<dd>
#Html.TextBoxFor(x => x.Name)
</dd>
<dt>Due Date:</dt>
<dd>
#Html.TextBoxFor(x => x.DueDate, new { #class = "date" })
<script type="text/javascript">
$(function () {
$('.date').datepicker({ dateFormat: "mm/dd/yy" });
});
</script>
</dd>
</dl>
<p>
<input type="submit" value="Add Assignment" id="new-assignment-submit" />
</p>
}
And here's the javascript:
$(function () {
$('#add-assignment-form').submit(function () {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
dataType: "json",
success: function (result) {
$('#output').html(result);
}
});
});
});
I have tried the event.stopPropogation() method, but didn't change my problem
EDIT: I've updated my javascript to the following, but I'm still getting the same result
$('#add-assignment-form').submit(function (event) {
event.preventDefault();
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
dataType: "json",
success: function (result) {
$('#output').html(result);
}
});
return false;
});
You need to return false; or event.preventDefault() to prevent the browser from submitting the form normally.
You have two options here,
Use Ajax.BeginForm() instead of Html.BeginForm() that you would use like
#using(Ajax.BeginForm( "AddAssignment", "Assignments",
new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "output"})) {
...
}
and get rid of the javascript code.
Or call event.prevendDefault() in
$('#add-assignment-form').submit(function (event) {
// ...
event.preventDefault();
});
Just specify
return false;
after your $.ajax() call
UPDATE
$(function () {
$('#add-assignment-form input[type=submit]').click(function () {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
dataType: "json",
success: function (result) {
$('#output').html(result);
}
});
return false;
});
});
Have you checked if there are other javascript errors on the page that might be causing this unexpected behaviour? I would suggest Firebug for FF or Javascript Console for Chrome.
Also, I've noticed that sometime FF has issues if you don't specify the script type, so make sure your type is set to "text/javascript".
hth,
-covo

Posting to action, mvc 3, not part of form

Can I post to action from view a filed of of my model ? Is is not part of the form. I just want to pass the myModel.someValue as argument to nextRelease action, hopefully without putting it anywhere in the form.
e.g.
View:
#model myModel
#using (Html.BeginForm("Search", "News", FormMethod.Get, new { id = "myform" }))
{
<div>myModel.someValue</div> //to show it has this field
<script type="text/javascript">
$('#nextbutton').click(function () {
$('#myform').attr("action", "/#controller.Language/news/nextRelease");
$("#submit").click();
});
</script>
}
Sure, you could use AJAX:
#model myModel
<script type="text/javascript">
$(function() {
$('#nextbutton').click(function () {
var url = '#Url.Action("NextRelease", "News")';
var dataToPost = #Html.Raw(Json.Encode(new { someValue = Model.SomeValue }));
$.post(url, dataToPost, function(result) {
alert('data successfully posted to server');
});
return false;
});
});
</script>
<button id="nextbutton">Next button</button>
or if you wanted to post not only a single property but the entire model:
var url = '#Url.Action("NextRelease", "News")';
var dataToPost = #Html.Raw(Json.Encode(Model));
$.ajax({
url: url,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(dataToPost),
success: function(result) {
alert('data successfully posted to server');
}
});

Resources