Can I post a JSON model from html.raw to controller?

后端 未结 1 1186
灰色年华
灰色年华 2021-01-28 17:00

I have a model I am passing to a view and using Html.Raw to encode it into a JSON object:

 var model = @Html.Raw(Json.Encode(Model));

On the pa

相关标签:
1条回答
  • 2021-01-28 17:34

    Change you code to

    $.ajax({
       type: 'POST',
       url: '@Url.Action("AddProducts")',
       data: model, // not stringified
       dataType: 'json',
       ....
    

    or

    $.post('@Url.Action("AddProducts")', model, function(data) {
      // do stuff with returned data
    });
    

    which will post back to

    [HttpPost]
    public ActionResult AddProducts(ProductModel model)
    {
       //do stuff with the model data
    }
    

    assuming the model in your view is ProductModel

    However, if your just wanting to post back the form, you can use var model = $('form').serialize(); rather than manually setting the properties of the object.

    0 讨论(0)
提交回复
热议问题