In the MVC application, the transmission of the model as a form data as part of the form data may bring challenges, especially when processing the entire model set. This article solves this problem by providing a comprehensive solution.
Challenge: The model serialization in JavaScript
When trying to use to attach the model to the form data in the form data in JavaScript, the model is usually serialized as a string, resulting in "
" representation.
formdata.append("model", model)
Solution: FormData serialization [object object]
In order to overcome this problem, please use the FormData construct function as follows the serialization model:
This method will automatically serialize models and any file generated byelement.
<code class="language-javascript">var formdata = new FormData($('form').get(0));</code>
<input type="file">
On the side of the controller, define an operation to receive the form data:
If your model does not include
<code class="language-javascript">$.ajax({ url: '@Url.Action("YourActionName", "YourControllerName")', type: 'POST', data: formdata, processData: false, contentType: false, });</code>
<code class="language-csharp">[HttpPost] public ActionResult YourActionName(YourModelType model) { }</code>
HttpPostedFileBase
<code class="language-csharp">[HttpPost] public ActionResult YourActionName(YourModelType model, HttpPostedFileBase myImage) { }</code>
The above is the detailed content of How Can I Pass Complex Models in Form Data for MVC Applications?. For more information, please follow other related articles on the PHP Chinese website!