Home > Web Front-end > JS Tutorial > How to Append and Receive a Model via FormData in ASP.NET MVC?

How to Append and Receive a Model via FormData in ASP.NET MVC?

Susan Sarandon
Release: 2024-12-22 06:12:10
Original
999 people have browsed it

How to Append and Receive a Model via FormData in ASP.NET MVC?

Appending and Receiving a Model in Formdata

To pass a model object as part of a formdata object and retrieve it in the controller, consider the following approach:

JavaScript:

  1. Create a FormData object:

    var formdata = new FormData($('form').get(0));
    Copy after login
  2. Convert the model to JSON using JSON.stringify():

    let model = {
      EventFromDate: fromDate,
      EventToDate: toDate,
      ...
    };
    const modelJson = JSON.stringify(model);
    Copy after login
  3. Append the JSON string to the formdata:

    formdata.append("model", modelJson);
    Copy after login

AJAX Call:

$.ajax({
  url: '@Url.Action("YourActionName", "YourControllerName")',
  type: 'POST',
  data: formdata,
  processData: false,
  contentType: false,
});
Copy after login

Controller:

  1. Decorate the action with the [HttpPost] attribute to indicate it receives HTTP POST requests.
  2. Declare a parameter of the appropriate model type:

    [HttpPost]
    public ActionResult YourActionName(YourModelType model)
    {
      // Your code to process the model here...
    }
    Copy after login
  3. ASP.NET MVC will automatically bind the JSON model string to the appropriate model type.

This approach allows you to append the entire model as JSON data to the formdata and retrieve it in the controller as a model object, enabling you to work with complex models in a controller action.

The above is the detailed content of How to Append and Receive a Model via FormData in ASP.NET MVC?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template