Submit json to MVC3 action

I have a form created using Knockout.js. When the user clicks the submit button, I convert the viewmodel back to the model and try to send the server. I tried:

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

But the object was empty 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"); }
});

This gets the data on the server with the correct data in it.

But I would like the data to be sent so that my controller can redirect to the correct view. Any suggestions?

+5
source share
2 answers

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

+11

, , JavaScript- - :

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

All Articles