Replace the Ajax.ActionLink by the same functionality with jQuery - asp.net-mvc

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.

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.

Dynamically added link action produces 'This request has been blocked...' error

When I add category in controller action I return JSON object:
return Json(new { categoryName = category.Name, isPrimary = isPrim ? "1" : "-1", categoryId = categoryId }, JsonRequestBehavior.AllowGet);
In JS handler function I add item on page:
...
var totalLink = "<li style='color: #bbbbbb;'>" + result.categoryName + "<a class='removeCategoryButton' href='#lnk#'>remove</a></li>";
var lnk = '#Url.Action("RemoveCategoryFromLocation", "Location", new{locationId = Model.Location.TicketId, categoryId=-1})';
totalLink = totalLink.replace('#lnk#', lnk);
totalLink = totalLink.replace('-1', result.categoryId);
$('#otherCategories').append(totalLink);
...
When I click on remove link I call the following function:
$(function () {
$('.removeCategoryButton').click(function (event) {
event.preventDefault();
$.ajax({
url: this.href,
type: 'POST',
context: this,
success: function (result) {
if(result.categoryName == 1) {
$(this).closest('li').remove();
}
}
});
return false;
});
});
But I get the following error:
This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.
This error happens only when I add item and want to remove it as soon after add on page. If I refresh page and click on remove link it works without problem.
Just to note when I get the error from above category is removed, so call works it just from some reason pop this error.
You seem to be adding the remove links dynamically and yet you have subscribed to the .click event handler only once when the DOM is ready. So make sure you do it in a lively manner. But since the .live() method is deprecated, depending on the jQuery version that you are using you should use either .delegate() or the .on() methods.
So with the latest version of jQuery it is recommended to use .on():
$(document).on(events, selector, data, handler);
$(document).on('click', '.removeCategoryButton', function () {
$.ajax({
url: this.href,
type: 'POST',
context: this,
success: function (result) {
if(result.categoryName == 1) {
$(this).closest('li').remove();
}
}
});
return false;
});
Notice that you no longer need to wrap this in a document.ready callback.

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();
});
});

bind the click event to all links in a div with a certain class name

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);
}
});
});

jQuery not submitting my form to an asp.net mvc controller

I'm trying to submit a form via ajax to an MVC controller.
HTML
<% using (Html.BeginForm("AskQuestion", "Home", FormMethod.Post, new { id="submitquestion"})) {%>
jQuery
$("#submitquestion").submit(function(event) {
event.preventDefault();
var form = $(this);
$.ajax({
url: '<%= Url.Action("AskQuestion", "Home") %>',
type: "Post",
data: form.serialize(),
success: function(result) {
if (result.success) {
//success method
}
}
});
I'm getting no javascript errors, and my controller is not getting hit when I set a breakpoint. However, if I just set this:
$("#submitquestion").submit();
The form submits.
What am I doing wrong? I want to submit the form via .ajax
Add new html button to submit and wirte your ajax submit in the click event like this,
$("#yourButton").click(function(event) {
event.preventDefault();
var form = $('#submitquestion');
$.ajax({
url: '<%= Url.Action("AskQuestion", "Home") %>',
type: "Post",
data: form.serialize(),
success: function(result) {
if (result.success) {
//success method
}
}
});
});
for submitting via ajax. add a button to html form
<input type="button" name="button" value="Test" id="test" />
And your jquery script should be like this,
$('#test').click(function () {
var formCollection = $(this).parents('form').serialize();
$.post('your url', formCollection, function (result) {
alert(result);
});
});
Hope this helps.

Resources