【问题标题】:Submit json to MVC3 action提交 json 到 MVC3 动作
【发布时间】:2011-08-27 12:52:03
【问题描述】:

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

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

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

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

这会将数据与正确的数据一起发送到服务器。

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

【问题讨论】:

    标签: jquery asp.net-mvc-3 knockout.js


    【解决方案1】:

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

    它的要点是他创建了一个名为“FromJson”的属性,看起来像:

    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 提交数据并使用适当的视图进行响应。

    【讨论】:

    • 非常感谢。我正在按照您提到的示例进行操作。我错过了属性部分。
    【解决方案2】:

    此外,它在提到的示例中,但您可能需要将 JavaScript 调用更改为:

    ko.utils.postJson(location.href, { viewModel: this.viewModel });
    

    【讨论】:

    • 其他答案的帖子中对此进行了介绍。
    猜你喜欢
    • 2013-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-06
    • 2011-01-11
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    相关资源
    最近更新 更多