如何在发布时在MVC2中返回JSON结果 [英] How to return JSON Result in MVC2 at Post

查看:110
本文介绍了如何在发布时在MVC2中返回JSON结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ajax post方法来发布类似:-

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

$(function(){

$(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

返回Json(new {结果=成功"}, JsonRequestBehavior.AllowGet);

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

我无法在div中获得结果;而不是将整个渲染页面作为完整文件返回.请告诉我该怎么做才能在页面上显示结果,并且还希望在不清除表单的情况下显示在同一页面上.

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 on 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.

型号:

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

控制器:

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" });
    }
}

查看:

<% 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" />
<% } %>

使用外部JavaScript毫不费力地AJAXify表单:

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;
    });
});

注意事项:

  • 我将.submit事件附加到形式为(#myForm)的if上,而在您的示例中,您使用的是#BtnName,它为表单看起来是一个可疑的名称.不幸的是,您尚未显示标记,因此我们不知道标记的实际含义
  • 我不再对形式(Home/Index)的url进行硬编码,而是依靠Html.BeginForm生成的URL.这样有两个好处:1.您现在可以将javascript放入一个单独的文件=>您不再将标记和脚本混合在一起,并且HTML页面现在变得更小,加载更快(缓存了外部静态javascript文件)和2 .当您将应用程序部署到其他服务器上或决定更改路由时,它仍然可以正常工作,而无需在js上进行任何修改.
  • 我不再使用contentType: 'application/json',因为当您使用$(this).serialize()时,这不会将表单序列化为JSON.它将其序列化为application/x-www-form-urlencoded样式.因此,您基本上是在引入一个矛盾: 您告诉服务器您将发送JSON请求,但实际上您不发送.
  • 我已删除了async: false属性,因为它会执行同步请求并在浏览器执行期间冻结浏览器.它不再是AJAX.因此,除非您要使用此功能,否则不要使用它.
  • 我已删除了dataType: 'json'参数,因为jQuery足够聪明,可以从实际响应Content-Type标头中推断出此参数,并自动解析返回的JSON,并将其作为可直接使用的javascript对象传递给成功回调.
  • 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.

这篇关于如何在发布时在MVC2中返回JSON结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆