How to use Ajax.BeginForm MVC helper with JSON result?

喜欢而已 提交于 2019-11-27 03:41:32
Kobi

Try this:

var json_data = content.get_response().get_object();

this will give you result in JSON format and you can use json_data[0] to get the first record

You can use OnFailure and OnSuccess instead of OnComplete; OnSuccess gives you the data as a proper JSON object. You can find the callback method signatures burried in ~/Scripts/jquery.unobtrusive-ajax.min.js which you should load on your page.

In your Ajax.BeginForm:

new AjaxOptions
    {
        OnFailure = "onTestFailure",
        OnSuccess = "onTestSuccess"
    }

Script block:

<script>
//<![CDATA[

    function onTestFailure(xhr, status, error) {

        console.log("Ajax form submission", "onTestFailure");
        console.log("xhr", xhr);
        console.log("status", status);
        console.log("error", error);

        // TODO: make me pretty
        alert(error);
    }

    function onTestSuccess(data, status, xhr) {

        console.log("Ajax form submission", "onTestSuccess");
        console.log("data", data);
        console.log("status", status);
        console.log("xhr", xhr);

        // Here's where you use the JSON object
        //doSomethingUseful(data);
    }

//]]>
</script>

These signatures match success and error callbacks in $.ajax(...), which might not be such a surprise after all.

This was tested using with 1.6.3 and 1.7.2.

Russel

Try using the below code:

<script type='text/javascript'>
    function onTestComplete(content) {
        var result = eval( '(' + content.get_data() + ')' );
        alert(result.UppercaseName);
    }
</script>

I use:

    function onTestComplete(data, status, xhr) {
       var data2 = JSON.parse(data.responseText);
       //data2 is your object
    }

Make sure you have included MicrosoftAjax.js and MicrosoftMvcAjax.js. Then use the following calls on the returned context to get a json object out of the return.

var json = context.get_data();
var data = Sys.Serialization.JavaScriptSerializer.deserialize(json);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!