将 json 提交给 MVC3 操作 [英] Submit json to MVC3 action

查看:16
本文介绍了将 json 提交给 MVC3 操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用 Knockout.js 创建的表单.当用户按下提交按钮时,我将视图模型转换回模型并尝试提交到服务器.我试过了:

I have a form created with Knockout.js. When the user presses the submit button, I convert the viewmodel back in a model and am trying to submit to the server. I tried:

ko.utils.postJson(location.href, ko.toJSON(viewModel));

但是当它到达服务器时对象是空白的.我切换到这个代码:

But the object was blank when it hit the server. I switched to this code:

$.ajax({
    url: location.href, 
    type: "POST",
    data: ko.toJSON(viewModel),
    datatype: "json",
    contentType: "application/json charset=utf-8",
    success: function (data) { alert("success"); }, 
    error: function (data) { alert("error"); }
});

这会将包含正确数据的数据发送到服务器.

That gets the data to the server with the correct data in it.

但我想要的是提交数据,以便我的控制器可以重定向到正确的视图.有什么建议吗?

推荐答案

Steve Sanderson 有一个较旧的示例,演示如何在控制器操作中正确绑定提交的 JSON 数据:http://blog.stevensanderson.com/2010/07/12/editing-a-variable-length-list-knockout-style/

Steve Sanderson has an older sample that demonstrates getting submitted JSON data to be bound properly in your controller action here: http://blog.stevensanderson.com/2010/07/12/editing-a-variable-length-list-knockout-style/

其要点是他创建了一个名为FromJson"的属性,如下所示:

The gist of it is that he creates an attribute called "FromJson" that looks like:

public class FromJsonAttribute : CustomModelBinderAttribute
{
    private readonly static JavaScriptSerializer serializer = new JavaScriptSerializer();

    public override IModelBinder GetBinder()
    {
        return new JsonModelBinder();
    }

    private class JsonModelBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var stringified = controllerContext.HttpContext.Request[bindingContext.ModelName];
            if (string.IsNullOrEmpty(stringified))
                return null;
            return serializer.Deserialize(stringified, bindingContext.ModelType);
        }
    }
}

然后,动作看起来像:

    [HttpPost]
    public ActionResult Index([FromJson] IEnumerable<GiftModel> gifts)

现在,您可以使用 ko.utils.postJson 提交数据并以适当的视图进行响应.

Now, you could use ko.utils.postJson to submit your data and respond with an appropriate view.

这篇关于将 json 提交给 MVC3 操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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