Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
402 views
in Technique[技术] by (71.8m points)

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

I'm trying to use the ASP.NET MVC Ajax.BeginForm helper but don't want to use the existing content insertion options when the call completes. Instead, I want to use a custom JavaScript function as the callback.

This works, but the result I want should be returned as JSON. Unfortunately, the framework just treats the data as a string. Below is the client code. The server code simply returns a JsonResult with one field, UppercaseName.

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

<% using (Ajax.BeginForm("JsonTest", new AjaxOptions() {OnComplete = "onTestComplete" })) { %>
    <%= Html.TextBox("name") %><br />
    <input type="submit" />
<%} %>

Instead of showing the uppercase result, it is instead showing undefined. content.get_data() seems to hold the JSON, but only in string form. How do I go about converting this to an object?

All of this seems a bit convoluted really. Is there a better way to get at the resulting content using Ajax.BeginForm? If it's this hard, I may skip Ajax.BeginForm entirely and just use the jQuery form library.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...