Passing a complex model set through formdata can be a challenge, but using a combination of jQuery serialization and MVC controller binding, it's possible to achieve this effectively.
To convert the model set into FormData, you can utilize jQuery's FormData object along with form serialization. If the model is bound to the view within form tags, serialize it using:
var formdata = new FormData($('form').get(0));
This will automatically include any model properties bound to form controls, including file inputs.
Submit the formdata to the controller using an AJAX request:
$.ajax({ url: '@Url.Action("YourActionName", "YourControllerName")', type: 'POST', data: formdata, processData: false, contentType: false, });
By setting processData and contentType to false, jQuery will allow the formdata to be sent as-is.
In your controller, you can define a strongly-typed method that will bind to the model set:
[HttpPost] public ActionResult YourActionName(YourModelType model) { }
MVC's model binding system will automatically populate the model from the formdata based on its property names.
If you need to include additional non-model properties in the formdata, simply use:
formdata.append('someProperty', 'SomeValue');
This allows you to extend the formdata with custom values that can be accessed in the controller.
The above is the detailed content of How to Pass a Complex Model Set via FormData to an MVC Controller?. For more information, please follow other related articles on the PHP Chinese website!