Reputation: 1
I am a fan of using Ajax helpers inside my asp.net mvc web applications. I used Ajax.BeginForm
and Ajax.Actonlink
frequently.
But I recently came across a more standard and more maintainable way to manage my forms and links.
So instead of writing something such as :-
@Ajax.ActionLink("Show Servers", "CustomerServer","Customer",
new {customerID = Model.AccountDefinition.ORG_ID},
new AjaxOptions {
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "detail" ,
LoadingElementId = "progress",
OnSuccess="detailsuccess",
}
)
I can define a regular <a>
and define its target url as follows:-
<a data-modal='' href="@Url.Action("CustomerServer","Customer", new {customerID = Model.AccountDefinition.ORG_ID})" title='GetListCustomer'> Show Servers</a>
And then to define a javascript as the following, that will take the role of the Ajax helpers. It will perform similar calls to the Ajax.ActionLink
& also when a form is being submitted it will perform a similar call that is being generated by Ajax.Beginform
using the bindForm(this);
function, as follows :-
$(document).on('click', 'a[data-modal]', function (e){
$('#myModalContent').css({ "max-height": screen.height * .82, "overflow-y": "auto" }).load(this.href, function () {
$('#myModal').modal({
//code goes here..
handle: ".modal-header"
});
$('#myModalContent').removeData("validator");
$('#myModalContent').removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse('#myModalContent');
bindForm(this);
$("input[data-autocomplete-source]").each(function () {
var target = $(this);
target.autocomplete({
source: target.attr("data-autocomplete-source"), minLength: 1, delay: 1000, appendTo: $("#myModal")
});
});
});
return false;
});
});
});
function bindForm(dialog) {
$('form', dialog).submit(function () {
$('.btn.btn-primary,.btn.btn-danger').prop("disabled", "disabled");
$('#progress').show();
if ($(this).valid()) {
$.ajax({
//code goes here
});
});
}
}
});
}
});
}
});
I found the second approach more standard and maintainable. Especially because I do not have to hard code the ajax setting on each ajax.actionlink
; InsertionMode
, UpdateTargetId
, OnSuccess="detailsuccess"
,etc on each ajax helper component.
So can anyone advise on the pros and cons of using these two approaches?
Upvotes: 0
Views: 1577
Reputation: 1561
I asked myself more or less the same thing. Then I stumbled over a very interesting Microsoft Jump Start video about Developing ASP.NET MVC 4 Web Applications.
Take a look at the chapter Developing ASP.NET MVC Views. You will find the answer in the Lesson 2: Using HTML Helpers.
As they explain in the video, ActionLink understands routing, it understands your model and generates automatically the right url if you change you're routing. UrlAction does not, it just creates the url you specified in your code.
By the way that's the real advantage of all html-helpers. They are built-in and know about what's going on with your application.
Upvotes: 2