"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to append and receive models through FormData in ASP.NET MVC?

How to append and receive models through FormData in ASP.NET MVC?

Posted on 2025-04-13
Browse:963

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3