Some interesting behavior I noticed recently about the Microsoft MVC 3 jQuery library jquery.unobtrusive-ajax.js is the ability to pass you own arguments into the handler.
Normally you have probably used it like this:
@using (Ajax.BeginForm(new AjaxOptions{OnComplete = "DefaultEditOnComplete"})) { //Person data and submit button }
This works pretty well but it’s not very clear if/how you could pass additional arguments into the OnComplete (possibly to get some code reuse anyone?). If you take a look at the jquery.unobtrusive-ajax.js source however it becomes apparent that you can actually pass any (*see notes at end of post) arguments you want into your OnComplete.
Here is an example of just that:
@using (Ajax.BeginForm(new AjaxOptions{OnComplete = "DefaultEditOnComplete(xhr, status, 'Person')"})) { //Person data and submit button }
Here is what the OnComplete JavaScript function looks like:
function DefaultEditOnComplete(xhr, status, entityName) { //xhr - the ajax response //status - the response text, ex. "success" //entityName - your custom argument, in this example 'Person' alert('DefaultEditOnComplete fired for ' + entityName); }
This should work fine for all the types of events specified in AjaxOptions, but different argument names are available for the different events:
- OnBegin – xhr
- OnComplete – xhr, status
- OnSuccess – data, status, xhr
- OnFailure – xhr, status, error
*I have noticed one problem with passing arguments, do not include a ‘.’ in any passed arguments. The function ‘getFunction’ does a split on ‘.’ on passed arguments presumably for some JavaScript namespacing/method purposes?
thanks
Thanks mate. Very helpful.
Great stuff, this helped me a lot.
Scoured the net and couldn’t find the OnFailure parameters in order to get the actual error message, until I found this. Thanks!!
Hi,
If we have multiple buttons how to idenfity which button is clicked in OnComplete mehtod.
Thanks,
RamiReddy
If I have 2 Buttons
I binded to both button AAK and Button PAAK
Now when I click karivepak what will happen
DLN Raju