Submit json to MVC3 action

前端 未结 2 1534
借酒劲吻你
借酒劲吻你 2020-12-25 10:18

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:

相关标签:
2条回答
  • 2020-12-25 10:59

    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/

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

    Then, the action looks like:

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

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

    0 讨论(0)
  • 2020-12-25 11:05

    Also, it's in the example mentioned, but you may need to alter your JavaScript call to something like:

    ko.utils.postJson(location.href, { viewModel: this.viewModel });
    
    0 讨论(0)
提交回复
热议问题