Model Binding using FromForm in ASP.NET Core Web API

Model Binding Using FromForm in ASP.NET Core Web API

In this article, I will discuss How to Implement Model Binding Using FromForm in ASP.NET Core Web API Application with Examples. Please read our previous article discussing Model Binding Techniques in ASP.NET Core Web API with Examples.

Model Binding Using FromForm in ASP.NET Core Web API

In ASP.NET Core Web API, model binding refers to the process of mapping request data to action method parameters. The FromForm attribute is used to bind data from an HTTP request form body to a method parameter. This is particularly useful when dealing with forms that submit data via POST requests, especially in scenarios where you’re uploading files or sending data in a format that mimics a traditional HTML form.

How Does FromForm Work in ASP.NET Core Web API?

When a client sends a request to an ASP.NET Core Web API, the framework tries to map the incoming request data to the parameters of the action method. If an action method parameter is decorated with the [FromForm] attribute, ASP.NET Core will try to bind incoming request data from the form’s fields to the properties of the object parameter.

Note: The [FromForm] attribute is not limited to POST methods; it can be used with any HTTP method that supports body content, but it’s most commonly used with POST and PUT requests.

FromForm Example in ASP.NET Core Web API

Here’s a step-by-step example of how to use the [FromForm] attribute in an ASP.NET Core Web API project:

Create a Model

First, define a model that corresponds to the data you expect to receive from the form. For instance, if you are expecting to receive user information, you might create a model like this. So, create a class file named UserModel.cs and then copy and paste the following code:

namespace ModelBinding.Models
{
    public class UserModel
    {
        public string Name { get; set; }
        public string Email { get; set; }
        // Add other properties as needed
    }
}
Create an API Controller

Next, create a controller that will handle form submissions. In the controller, define an action method that uses the [FromForm] attribute to bind the posted form data to your model. So, create an API controller named UserController and then copy and paste the following code:

using Microsoft.AspNetCore.Mvc;
using ModelBinding.Models;
namespace ModelBinding.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        [HttpPost]
        public IActionResult CreateUser([FromForm] UserModel user)
        {
            // Handle the user data, e.g., save it to a database
            var response = new
            {
                Success = true,
                Message = $"User {user.Name} created successfully!",
                Code = StatusCodes.Status200OK
            };
            return Ok(response);
        }
    }
}
Testing the API

To test the API, you can use Postman or create a simple HTML form that posts data to your API endpoint. To test using Postman, open Postman, select the method type as POST, provide the endpoint URL in the request body, select form-data, provide the Key name same as your model name, select the type as text and provide the corresponding values, and finally click on the Send button as shown in the below image:

How to Implement Model Binding Using FromForm in ASP.NET Core Web API Application with Examples

Once you click on the Send button, then you will get the following response:

How to Implement Model Binding Using FromForm in ASP.NET Core Web API Application with Examples

Test using HTML form:

So, create an HTML file (file with .html or .html extension) and then copy and paste the following code. Please change the port number where your application is running.

<form action="https://localhost:7121/api/User" method="post">
    <input type="text" name="Name" placeholder="Name" required />
    <input type="email" name="Email" placeholder="Email" required />
    <button type="submit">Submit</button>
</form>

Now, once you open the HTML file in a web browser, then it will show the following. Please enter your Name and email and then click on the Submit button as shown in the below image:

How to Implement Model Binding Using FromForm in ASP.NET Core Web API

Make sure your server is running, and then submit the form. Your API should receive the form data, bind it to the UserModel object, and execute the logic defined in the CreateUser method. Once you click on the Submit button, then you will see the following response in the browser:

How to Implement Model Binding Using FromForm in ASP.NET Core Web API

Points to Remember:
  • The [FromForm] attribute is designed to handle application/x-www-form-urlencoded and multipart/form-data content types, which are commonly used for forms.
  • For file uploads, use IFormFile within your model and bind it using the [FromForm] attribute.
  • Ensure client requests are properly formatted and match the expected model structure to avoid binding issues.
Handling File Uploads Using FromForm in ASP.NET Core Web API:

The FromForm attribute can also handle file uploads. You can include properties of type IFormFile within your model to bind to uploaded files. Let us understand this with one example. So, modify the UserModel as follows:

namespace ModelBinding.Models
{
    public class UserModel
    {
        public string Name { get; set; }
        public string Email { get; set; }
        public IFormFile ProfilePicture { get; set; }
        // Add other properties as needed
    }
}
Modifying the User Controller:

Next, modify the User Controller as follows. If your form includes file uploads, your model can include one or more IFormFile properties. The [FromForm] attribute ensures that these files are bound correctly to the model. You can then process these files in your action method, for example, by saving them to a server directory.

using Microsoft.AspNetCore.Mvc;
using ModelBinding.Models;
namespace ModelBinding.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        [HttpPost]
        public async Task<IActionResult> CreateUser([FromForm] UserModel user)
        {
            if (user.ProfilePicture != null)
            {
                var uploadsFolderPath = Path.Combine(Directory.GetCurrentDirectory(), "Uploads");
                if (!Directory.Exists(uploadsFolderPath))
                {
                    Directory.CreateDirectory(uploadsFolderPath);
                }

                var filePath = Path.Combine(uploadsFolderPath, user.ProfilePicture.FileName);
                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    await user.ProfilePicture.CopyToAsync(stream);
                }

                // Handle the user data, e.g., save it to a database
                var response = new
                {
                    Success = true,
                    Message = $"User {user.Name} created successfully!",
                    ProfilePictureName = user?.ProfilePicture?.FileName,
                    Code = StatusCodes.Status200OK
                };
                return Ok(response);
            }
            return BadRequest(ModelState);
        }
    }
}
Testing the API

To test using Postman, open Postman, select the method type as POST, provide the endpoint URL, in the request body select form-data, provide the Key name same as your model name, select the type as text (Name and Email) and file (Profile Picture) as per the data and provide the corresponding values for Name and Email, select the Profile Picture for the File type and finally click on the Send button as shown in the below image. This will also automatically set the Content-Type header value to multipart/form-data in the request header.

Handling File Uploads Using FromForm in ASP.NET Core Web API

Once you click on the Send button, then you will get the following response:

Handling File Uploads Using FromForm in ASP.NET Core Web API

Now, if you verify the project directory, then it should create the Uploads folder, and within that folder, it should store the uploaded image as shown in the below image:

Handling File Uploads Using FromForm in ASP.NET Core Web API

Test using HTML form:

So, test using HTML and then copy and paste the following code. Please change the port number where your application is running.

<form action="https://localhost:7121/api/User" method="post" enctype="multipart/form-data">
    <input type="text" name="Name" placeholder="Name" required /> </br>
    <input type="email" name="Email" placeholder="Email" required /></br>
    <input type="file" name="ProfilePicture" id="ProfilePicture"></br>
    <button type="submit">Submit</button>
</form> 

Now, once you open the HTML file in a web browser, then it will show the following. Please enter your Name and Email, then select the file and then click on the Submit button as shown in the below image:

blank

Make sure your server is running, and then submit the form. Your API should receive the form data, bind it to the UserModel object, and execute the logic defined in the CreateUser method. Once you click on the Submit button, then you will see the following response in the browser:

blank

Advantages of Using FromForm
  • Clarity: It explicitly indicates that the data should be bound from the form body, improving the readability of the code.
  • Flexibility: It supports complex types and file uploads, making it versatile for various scenarios.
  • Validation: ASP.NET Core model validation can be applied, allowing for easy data validation.
When to Use FromForm Model Binding in ASP.NET Core Web API

In ASP.NET Core Web API, the FromForm model binding attribute is used to bind form data to parameters or properties of a controller’s action method. It is particularly useful in scenarios where the client sends data as application/x-www-form-urlencoded, a common content type for form submissions. Here’s when to use FromForm in your ASP.NET Core Web API:

  • Handling HTML Form Submissions: When your API endpoint needs to process data submitted from an HTML form, especially in situations where the client is a web browser submitting form data directly to the server without JavaScript.
  • File Uploads: FromForm is especially useful when you need to handle file uploads along with other form data. In this scenario, the form is typically encoded as multipart/form-data, and the FromForm attribute can bind the text fields as well as the file inputs from the form.
  • Compatibility with Existing Front-end: If your API is interacting with existing front-end applications or third-party clients that send requests with content type application/x-www-form-urlencoded or multipart/form-data, using FromForm allows you to directly map incoming data to your models without needing to change the client’s data submission method.

In the next article, I will discuss Model Binding Using FromQuery in ASP.NET Core Web API with Examples. In this article, I try to explain Model Binding Using FromForm in ASP.NET Core Web API with Examples, and I hope you enjoy this article “Model Binding Using FromForm in ASP.NET Core Web API”.

Leave a Reply

Your email address will not be published. Required fields are marked *