ASP.NET - Ajax.BeginForm OnSuccess call back with params

一曲冷凌霜 提交于 2019-11-27 02:42:44

问题


I want to add more params to my OnSuccess call back (but keep the ajax context variable).
What I did is:

 using (Ajax.BeginForm("Register", new AjaxOptions() {
   OnSuccess = "new function(arg){HandleBasicForm(arg , 'MyCustomVariable')}",
    ...

The JS function:

function HandleBasicForm(ajaxContext , myCustomVariable){
            var content = ajaxContext.get_response().get_object();
            ....
        }

But ajaxContext is null.
How do I do that?


回答1:


Since you're using get_response() I'm guessing that you're not using the unobtrusive javascript stuff (in MVC3 you've set HtmlHelper.UnobtrusiveJavaScriptEnabled = false) and you're referencing the MicrosoftAjax,js and MicrosoftMvcAjax.js files. If that's the case you just need to drop the new keyword.

 using (Ajax.BeginForm("Register", new AjaxOptions() { OnSuccess = "function(arg){HandleBasicForm(arg , 'MyCustomVariable')}"})

If you are using the MVC3 unobtrusive javascript support with jquery.unobtrusive-ajax.js then you can use the implicitly available xhr and data variables instead.

using (Ajax.BeginForm("Register", new AjaxOptions() { OnSuccess = "HandleBasicForm(data, 'MyCustomVariable')"})

In your handler there would be no need to use get_response().get_object() since the deserialized JSON data would be passed in to your handler directly.

function HandleBasicForm(data, myCustomVariable){
    var someValue = data.someProperty; //work with data object returned
    ....
}



回答2:


OnSuccess receives data, status, xhr from the server:

OnSuccess = "myJsMethod(data, status, xhr)"

And then its equivalent JavaScript method would be:

 function myJsMethod(data, status, xhr) {
}

Now your controller should return:

return Json(new { param1 = 1, param2 = 2, ... }, JsonRequestBehavior.AllowGet);

Then in myJsMethod you will have access to data.param1 and so on.



来源:https://stackoverflow.com/questions/8034530/asp-net-ajax-beginform-onsuccess-call-back-with-params

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!