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
Susan SarandonOriginal
2024-12-22 06:12:10961browse

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));
  2. Convert the model to JSON using JSON.stringify():

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

    formdata.append("model", modelJson);

AJAX Call:

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

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...
    }
  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:
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