开发者

How to return JSON Result in MVC2 at Post

I am using ajax post method to post the form like :-

$(function () {

        $('#BtnName').submit(function () {
            $.ajax({
                url: 'Home/Index',
                type: "POST",
                data: $(this).serialize(),
                dataType: "json",
                async:false,
                contentType: 'application/json; charset=utf-8',
                success: function (data) { var message = data.Result; $("#Result").html(message); },
               

            });
            return false;
        });
    });

At the action controller i m returning

return Json(new { Result = "Success" }, JsonRequestBehavior.AllowGet);

i m not able to get the Result in the div ; instead of this its returning the whole render page as complete file. Please tell me what should i do do to show the result 开发者_如何学JAVAon the page and also want to on the same page without clearing the form.


OK, the code bits contained in your question are absolutely insufficient to draw any conclusions. So let's do a full example.

Model:

public class MyViewModel
{
    public string Foo { get; set; }
}

Controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new MyViewModel());
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        // TODO : process the model ...

        return Json(new { Result = "Success" });
    }
}

View:

<% using (Html.BeginForm(null, null, FormMethod.Post, new { id = "myForm" })) { %>
    <%= Html.LabelFor(x => x.Foo) %>
    <%= Html.EditorFor(x => x.Foo) %>
    <input type="submit" value="Save" />
<% } %>

External javascript to unobtrusively AJAXify the form:

$(function () {
    $('#myForm').submit(function () {
        $.ajax({
            url: this.action,
            type: this.method,
            data: $(this).serialize(),
            success: function (data) {
                var message = data.Result; 
                $('#Result').html(message);
            }
        });
        return false;
    });
});

Things to notice:

  • I am attaching the .submit event to the if of the form (#myForm), whereas in your example you are using #BtnName which looks a strangely suspicious name for a form. Unfortunately you haven't shown your markup so we don't know what it actually represents
  • I am no longer hardcoding the url of the form (Home/Index) but relying on the one generated by the Html.BeginForm. There are two benefits of this: 1. youcan now put your javascript into a separate file => you are no longer mixing markup and script and your HTML pages now become smaller and faster to load (the external static javascript files are cached) and 2. when you deploy your application on some other server or you decide to change your routes it will still work without any modification on your js.
  • I am no longer using contentType: 'application/json' because when you use $(this).serialize() this doesn't serialize the form into JSON. It serializes it into a application/x-www-form-urlencoded style. So you are basically introducing a contradiction: you are telling the server that you will send a JSON request but in practice you don't.
  • I have removed the async: false attribute as this does a synchronous request and freezes the browser during its execution. It is no longer AJAX. So unless you want this, don't use it.
  • I have removed the dataType: 'json' parameter as jQuery is intelligent enough to deduce this from the actual response Content-Type header and automatically parse the returned JSON and pass it to the success callback as a javascript object that you could directly use.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜