Model Binding : Passing Data from View to Controller - TekTutorialsHub (2023)

Environment Tag Helper

Model Validation

In this Model binding in ASP.NET Core article, we will learn How to pass data from View to Controller. We learn what is Model binding is and how it works. The ASP.NET core allows us to bind data from various binding sources like HTML Forms using [FromForm], Route Values using [FromRoute], Query string using [FromQuery], Request body using [FromBody] and From Request Header using [FromHeader]. We will look at all these in this chapter

Here is the link to previous tutorials

  1. Model and ViewModel
  2. Passing ViewModel from Controller to View
  3. Building Forms in Views
  4. Creating Strongly typed Views
  5. Using Tag Helpers to Create Forms

Table of Contents

  • What is Model Binding
  • Getting Form Data in Controller
  • How Model Binding works
    • Model Binder
    • ModelState
  • Life without model binding
    • Accessing the HTML Forms directly
    • Accessing the query string directly
    • Accessing the Request Headers directly
    • Accessing the Route Data directly
  • Model Binding Sources
  • Getting data from Form and query string
  • Controlling the Binding Source
    • [FromForm]
    • [FromRoute]
    • Binding Query string using [FromQuery]
    • Binding to Request body Using [FromBody]
    • Binding from Request Header using [FromHeader]
    • Disabling Binding with [BindNever]
    • Forcing Binding with [BindRequired]
  • Summary

What is Model Binding

The Model binding is the process of mapping the data posted over an HTTP request to the parameters of the action method in the Controller.

The HTTP Request can contain data in various formats. The data can contain in the HTML form fields. It could be part of the route values. It could be part of the query string or it may contain in the body of the request.

ASP.NET Core model binding mechanism allows us easily bind those values to the parameters in the action method. These parameters can be of the primitive type or complex type.

Getting Form Data in Controller

In the tutorial on Tag Helpers, we created a simple Form, which accepted the Product detail. When the user clicked on the submit button it posted the data to the create controller action method.

In the above project, we created a ProductEditModel object, which contains the details of the product that needs to be created or edited

1

2

3

4

5

6

7

8

9

public class ProductEditModel

{

public int ID{ get; set; }

public string Name { get; set; }

public decimal Rate { get; set; }

public int Rating { get; set; }

}

A form is created to which contains three form fields. Name, Rate and Rating.

1

2

3

4

5

6

7

8

9

10

11

12

<form action="/home/Create" method="post">

<label for="Name">Name</label>

<input type="text" name="Name" />

<label for="Rate">Rate</label>

<input type="text" name="Rate" />

<label for="Rating">Rating</label>

<input type="text" name="Rating" />

<input type="submit" name="submit" />

</form>

The Create action method in the HomeController.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

[HttpPost]

public IActionResult Create(ProductEditModel model)

{

string message = "";

if (ModelState.IsValid)

{

message = "product " + model.Name + " created successfully" ;

}

else

{

message = "Failed to create the product. Please try again";

}

return Content(message);

}

On the submission of the above form, the values in the form fields are automatically mapped to the ProductEditModel object of the action method of the controller.

1

2

3

public IActionResult Create(ProductEditModel model)

This automatically happens behind the scene by a Process called Model Binding. The Model binder looks for a match in the form fields, Route Values and query strings.

How Model Binding works

The image below illustrates how model binding works.

Model Binding : Passing Data from View to Controller - TekTutorialsHub (1)

When the user clicks on the Submit button a Post request is sent to the server along with the Form Data, Query String, Route Parameters etc.

The MVCRouteHandlerof the Routing Engine handles the incoming request and is responsible for invoking the action method create.

The Model binder kicks in just before the action method invocation.It looks for a match in the form data, query strings, and request parameters in the HTTP Request data.

Then, It tries to bind the values to the action parameter by Name.

For Example, the “name” form field is mapped to the “name” property of the ProductEditModel. Rate Form field is mappedto the Rate Property and henceforth.

Model Binding : Passing Data from View to Controller - TekTutorialsHub (2)

For the Binding to work correctly

  • The Property Name must match with the Request data
  • Properties must be defined as public settable

Model Binder

The Model binder is responsible to populate the action method parameter. The Model Binder is created by the model binder provider.

The Model binder must implement the provider interface is IModelBinderProvider.

Which, means you can create your ownModel binderor extend the existing one by implementing the IModelBinderProvider. The customer model binder must be registered in the ModelBinderProviders collection at the startup.cs as follows.

1

2

3

4

5

6

services.AddMvc(options =>

{

options.ModelBinderProviders.Add(new CustomModelBinderProvider());

});

ModelState

If Model binder fails to bind the incoming Request data to thecorrespondingmodel property, then it does not throw any error but fails silently. But it updates ModelState object with the list of errors and sets the isValid property to false.

Hence, checking for ModelState.isValid tells us whether the model binding succeeded or not.

For Example, in the above example clicking on the submit button without entering any data in any of the fields will result in validation failure and hence the ModelState.isValid becomes false.

Life without model binding

Before further exploring the Model binding, we need to understand how you can access data without using the model binding.

Accessing the HTML Forms directly

To do that we need to access the Request object to access the values the data.

Open the code, which we created in the previous tutorial,

Add the new action method NoModelBinding action method

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

[HttpPost]

public IActionResult NoModelBinding()

{

ProductEditModel model = new ProductEditModel();

string message = "";

model.Name = Request.Form["Name"].ToString();

model.Rate = Convert.ToDecimal( Request.Form["Rate"]);

model.Rating =Convert.ToInt32( Request.Form["Rateing"]);

message = "product " + model.Name + " created successfully";

return Content(message);

}

And change to

1

2

3

<form action="/home/NoModelBinding" method="post">

Accessing the query string directly

Similarly, you can access the query string values directly using the Request.Query collection, which is parsed from the Query String.

For Example Request.Query[“id”].ToString() returns the value of id query string.

The Request.QueryString.HasValue will let you know if the Query string is present in the URL and Request.QueryString.Value will return the raw query string.

Accessing the Request Headers directly

Similarlyyou can usethe Request.Headers collection to access the values present the HTTP Headers

Accessing the Route Data directly

To Access the route you need to Override the OnActionExecuting method as shown below

1

2

3

4

5

6

7

8

9

using Microsoft.AspNetCore.Mvc.Filters;

public override void OnActionExecuting(ActionExecutingContext context)

{

string id = context.RouteData.Values["id"].ToString();

base.OnActionExecuting(context);

}

As you can see it takes a lot of code to access the values posted over HTTP Request. The ASP.NET Core Model binding hides all those intricacies for us.

Model Binding Sources

As mentioned earlier, the model binder looks for the data from the various data sources. Here is the list of data sources in the order that model binding looks through them

  • HTML Form Values
  • Route Values
  • Query Strings

The Model binder can also look for the data from the following sources also, but to do that we need to specify the binding source explicitly.

  • Request Body
  • Request Header
  • Services

Getting data from Form and query string

Let us try to bind action parameter to both Form and query string. FormAndQuery action method as shown below

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

[HttpGet]

public IActionResult FormAndQuery()

{

return View();

}

[HttpPost]

public IActionResult FormAndQuery(string name,ProductEditModel model)

{

string message = "";

if (ModelState.IsValid)

{

message = "Query string "+ name + " product " + model.Name + " Rate " + model.Rate + " Rating " + model.Rating ;

}

else

{

message = "Failed to create the product. Please try again";

}

return Content(message);

}

Note that the Action Method FormAndQuery takes two arguments name and ProductEditModel.

1

2

3

public IActionResult FormAndQuery(string name,ProductEditModel model)

Next, create the view FormAndQuery and the following code.

1

2

3

4

5

6

7

8

9

10

11

12

<form action="/home/FormAndQuery/?name=Test" method="post">

<label for="Name">Name</label>

<input type="text" name="Name" />

<label for="Rate">Rate</label>

<input type="text" name="Rate" />

<label for="Rating">Rating</label>

<input type="text" name="Rating" />

<input type="submit" name="submit" />

</form>

The form has a namefield. We are also sending name=test as the query string to the controller action

1

2

3

<form action="/home/FormAndQuery/?name=Test" method="post">

In the above example, the parameter “name” appears twice as the part of the Form and also part of the query string

When this form is submitted, the “name” parameter is always mapped to the Form field and not to the query string.

That is because the Model binder always uses the following order to map the data source fields to the parameter. And the first match wins.

  1. Form Values
  2. Route Values
  3. Query strings

Since the Form Values has a name field, the name parameter is always populated by it.

We can change this behaviour by decorating the name parameter by using the [FromQuery] attribute.

Apply the [FromQuery] attribute to the name parameter as shown below

public IActionResult FormAndQuery([FromQuery] string name,ProductEditModel model)

Now, if you submit the form, the name parameter gets the value from the query string, while productEditModel correctly populated from the form values

Controlling the Binding Source

In the previous example, we used [FromQuery] attribute to force model binder to change its default behaviour and use query string as the source for binding.

The ASP.NET Core gives us several suchattributes to control and choose from what source we want to receive the binding data

  1. [FromForm]
  2. [FromRoute]
  3. [FromQuery]
  4. [FromBody]
  5. [FromHeader]
  6. [FromServices]

[FromForm]

The [FromForm] forces the model binder to bind the parameter to the fields of the HTML Forms.

1

2

3

4

5

6

[HttpPost]

public IActionResult Create([FromForm] ProductEditModel model)

{

}

[FromRoute]

The [FromRoute] forces the model binder to bind that parameter to Route data from the current request.

Let us see how to use it with a live example.

Create a FromRoute action method, which accepts the id and ProductEditModel

We have two id parameter. The MVC default route has Id Parameter, which is optional. The ProductEditModel also has an id property

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

[HttpGet]

public IActionResult FromRoute()

{

return View();

}

[HttpPost]

public IActionResult FromRoute(string id, ProductEditModel model)

{

string message = "";

if (ModelState.IsValid)

{

message = "Route " + id + " Product id " + model.id + " product " + model.Name + " Rate " + model.Rate + " Rating " + model.Rating;

}

else

{

message = "Failed to create the product. Please try again";

}

return Content(message);

}

Create FromRoute view

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

<form action="/home/FromRoute/Test" method="post">

<label for="id">id</label>

<input type="text" name="id" />

<label for="Name">Name</label>

<input type="text" name="Name" />

<label for="Rate">Rate</label>

<input type="text" name="Rate" />

<label for="Rating">Rating</label>

<input type="text" name="Rating" />

<input type="submit" name="submit" />

</form>

Note that we are invoking the controller action by using the “test” as the route value.

1

2

3

<form action="/home/FromRoute/Test" method="post">

Now, when you submit the form, the id parameter is always mapped to the id Form field and not from the route value.

Now Open the HomeController and apply [FromRoute] Attribute on the id Parameter as shown below.

1

2

3

public IActionResult FromRoute([FromRoute] string id, ProductEditModel model)

Now, when you submit the form the id is populated with “test”.

Binding Query string using [FromQuery]

[FromQuery] forces the model binder to bind the parameter to the value obtained from the query string.

Binding to Request body Using [FromBody]

[FromBody] forces the model binder to bind a parameter to data from the request body. The formatter is selected based on the content-type of the request.

The data in the request body come in the variety of formats including JSON, XML and many others. The Model binder looks at the content-type header to select the formatter to parse the data contained in the request body.

For example, when the content-type is “application/json”, the model binder uses the JsonInputFormatter class to parse the request body and map it to the parameter.

Binding from Request Header using [FromHeader]

[FromHeader] maps the request header values to the action parameter.

1

2

3

4

5

6

public IActionResult FromHeader( [FromHeader] string Host)

{

return Content(Host);

}

Disabling Binding with [BindNever]

The Tells the model binder to never bind to the Property.

For Example,

1

2

3

4

[BindNever]

public int Rating { get; set; }

Now, model binder ignore the Rating Property, even if the form has Rating field.

Forcing Binding with [BindRequired]

This is exactly opposite of BindNever. The field marked with BindRequired must always present in the form field and binding must occur, otherwise will Modelstate.isValid marked as false.

Summary

We looked at how you can pass data from view to controller using Model Binder, The Model binder automatically binds the fields to Model Property behind the scene. You can modify the default behaviour of the Model binder by using the various attributes like [FromForm], [FromQuery], [FromBody],[FromRoute],[FromHeader] , [FromServices] [BindNever] & [BindRequired] etc.

Environment Tag Helper

Model Validation

FAQs

How do you pass data from view to controller in MVC? ›

Views pass data to controller in one of two ways (ignoring JavaScript ajax calls).
  1. An anchor (<a>) where the data is passed as query string name/value parameters. The mvc data binding will bind the parameters to the controllers action parameters by name.
  2. A form post. The form data is again passed as names / value pairs.
May 8, 2022

How to pass model value from view to controller? ›

We bind a model to the view; that is called strongly type model binding.
  1. Create a Model for Simple Interest. ...
  2. We are passing an empty model to be bound to the view. ...
  3. Create a strongly typed view that has the same screen as in Figure 1.1. ...
  4. In the action method we pass a model as the parameter.
Nov 25, 2020

How to bind data from view to controller in MVC? ›

Step 1: Open the VS 2019 and select the ASP.NET core web application.
  1. Step 2: Select the template of the web application (MVC).
  2. Step 3: Go to the home controller and student basic type binding.
  3. Step 4: Create view as per the below given code example:
  4. Step 5: Now, press f5 and run the solution.
Feb 20, 2023

How does model binding works in model view controller? ›

Model binding is a process in which we bind a model to controller and view. It is a simple way to map posted form values to a . NET Framework type and pass the type to an action method as a parameter. It acts as a converter because it can convert HTTP requests into objects that are passed to an action method.

How to pass list from view to controller in MVC core? ›

You cannot pass an IList, or List from view to controller in MVC. As the other answer specifies, you cannot use a foreach and must use a for() loop to iterate through, referencing the indices with m => Model[i]. account_number.

How to pass JSON data from view to controller in MVC? ›

Sending Complex JSON Objects To ASP.NET MVC View Using JQuery Ajax
  1. Start Visual Studio.
  2. Select File, New, then New Project.
  3. Select Visual C# and in menu of C# select Web section.
  4. Select ASP.NET Web application and select ASP.NET MVC.
  5. Name your project and now follow the screenshots.
Dec 6, 2015

How to pass data from one view controller to another view controller? ›

You can pass data between view controllers in Swift in 6 ways:
  1. By using an instance property (A → B)
  2. By using segues with Storyboards.
  3. By using instance properties and functions (A ← B)
  4. By using the delegation pattern.
  5. By using a closure or completion handler.
  6. By using NotificationCenter and the Observer pattern.
Apr 10, 2023

How to pass label value from view to controller in MVC? ›

Label value cannot be sent to Controller directly and hence when the Submit Button is clicked and the Form is submitted, the Label value needs to be copied to a Hidden Field and then the value of the Label is extracted from the Hidden Field inside the Controller using Form Collection in ASP.Net MVC Razor.

How to pass data from one ViewController to another view controller in objective c? ›

Start creating the segue via a storyboard. Control + click the UI element you are going to use to make the bridge and drag to the second View Controller. Select the “Show” option from the “Action Segue” menu. Control + click the button and drag to the second ViewController, then select “Show.”

How to pass multiple values from view to controller in MVC? ›

Here I will explain ways one by one.
  1. Using Dynamic Model. ExpandoObject (the System. ...
  2. Using View Model. ViewModel is nothing but a single class that may have multiple models. ...
  3. Using ViewData. ViewData is used to transfer data from the controller to the view. ...
  4. Using ViewBag. ...
  5. Using Tuple. ...
  6. Using Render Action Method.
Jun 24, 2021

How to pass dynamic table values from view to controller? ›

  1. how to pass dynamic table values from view to controler.
  2. load the values dynamically from view to the controller.
  3. Pass the Value from view to controller.
  4. Seeking help in passing data using from view to controller in ASP.NET core.
  5. How to pass viewbag value from controller to html.editor helpermethod in view.
Nov 2, 2015

How to get value from model in view in MVC? ›

Go to Controller class which you have already created in previous step. Add namespace of model in controller class. In MVC we have four ways to pass data from controller to view.
...
Retrieve value in View:
  1. @{
  2. var emp = (Employee)Session["EmployeeSessionData"];
  3. }
Jan 19, 2016

What are the three 3 parts of model-view-controller pattern? ›

The Model-View-Controller (MVC) is an architectural pattern that separates an application into three main logical components: the model, the view, and the controller.

What is the difference between view model and view controller? ›

Model–view–controller (MVC) is a software architectural pattern for implementing user interfaces on computers. View is a user interface. View displays data from the model to the user and also enables them to modify the data. Controllers are responsible for controlling the flow of the application execution.

How to pass value from one cshtml to another cshtml? ›

The data from the Source cshtml page (View) will be posted (submitted) using Form Post to the Controller's Action method of the Destination cshtml page (View). Then finally, the received data will be displayed in the Destination cshtml page (View) using ViewBag.

How to pass DropDownList selected value from view to controller in MVC? ›

If you want to pass the selected value of your dropdown list into your controller, just add a string parameter with the name drpFields (same as the first parameter of your DropDownList method) into your temp action method.

How to pass CheckBox value from view to controller in MVC? ›

Getting CheckBox Values In ASP.NET MVC Controller
  1. Step 1 : Create an ASP.NET MVC Application. Now let us start with a step by step approach from the creation of simple MVC application as in the following: ...
  2. Step 2 : Add Model class. ...
  3. Step 3 : Add Controller. ...
  4. Step 4: Add View.
Oct 29, 2015

How to pass data from view to controller in MVC using AJAX? ›

Let's begin now.
  1. Create a new MVC web project and name it "MVCAjaxWithParam".
  2. Create a "Controllerss\HomeController. ...
  3. Now, create the subsequent view "Views\Home\Index. ...
  4. Now, create the JavaScript file "Scripts\script-custom-ajax. ...
  5. Now, execute the provided solution and you will be able to see the following in action i.e.
Nov 2, 2020

How to send JSON data to controller? ›

Posting JSON Data to an MVC Controller via Ajax
  1. Go ahead and enter your First and Last name, and select your favorite bands:
  2. Now set a break point on the PersonController on both the BadSave and the GoodSave actions and click the Bad Submit and Good Submit buttons in the UI.
Feb 27, 2013

How to pass JSON array to controller in MVC? ›

Linked
  1. Passing JSON Object and List of Objects to ASP.Net Controller.
  2. JSON.stringify() ModelBinding returns null model.
  3. Posting an array from view to controller using jQuery.
  4. ASP.Net Controller improperly Deserializing nested list of objects.
  5. Ajax sends array to controller without data in it.
  6. Bind JSON List to View Model.
Dec 8, 2012

How is data sent between controller and view? ›

The other way of passing the data from Controller to View can be by passing an object of the model class to the View. Erase the code of ViewData and pass the object of model class in return view. Import the binding object of model class at the top of Index View and access the properties by @Model.

Can we pass temp data from view to controller? ›

TempData is used to transfer data from view to controller, controller to view, or from one action method to another action method of the same or a different controller. TempData stores the data temporarily and automatically removes it after retrieving a value.

How to pass data from view to controller in MVC using TempData? ›

To pass the strongly typed data from Controller to View using TempData, we have to make a model class then populate its properties with some data and then pass that data to TempData as Value and selecting Key's name is the programmer's choice.

How to pass data from one ViewController to another using segue in Swift? ›

Passing data using segues:
  1. You need to create a segue between viewcontrollers in storyboard.
  2. Assign an identifier name to segue.
  3. use prepare(for:sender:) method to pass the function.

Can a ViewController have more than one ViewModel? ›

If a ViewController is complex (it contains many different elements or provides many interactions) then it's ViewModel will be complex too. Following the Single Responsibility Principle we can create more than one ViewModel for a single ViewController.

How to pass object from one controller to another in Spring MVC? ›

  1. Using Model attribute argument in the @RequestMapping method and access the value as below. Model. ...
  2. Using RequestContextUtils, the static method getInputFlashMap() accepts HttpServeltRequest as an argument and it returns a Map. ...
  3. Access directly using model parameter from the @RequestMapping method in the jsp page.
Sep 27, 2015

How to pass data from view to controller in CI? ›

How to Pass Data From Controller to View in CodeIgniter
  1. Create a View.
  2. Load the View.
  3. Pass array from the controller to view.
  4. Load Multiple Views.
  5. Sort Views in Subfolders.
  6. Add Dynamic Data to Views.
  7. Create the Loops.
  8. Returning View as Data.
Mar 30, 2022

How to pass data from view to controller using Ajax in MVC core? ›

Post Data without Form Serialize
  1. Create an action method in controller. ...
  2. Create a model class. ...
  3. Give an appropriate name to your model. ...
  4. Create properties in your model class. ...
  5. Create a new action method which will be called from Ajax. ...
  6. Create view for appropriate to your requirement and model.
Sep 5, 2022

How to pass data from API to controller? ›

Example of the application.
  1. Create a Web API application as in the following: Start Visual Studio 2012. ...
  2. Create Model Class: In the "Solution Explorer". ...
  3. Create a Controller: In the "Solution Explorer". ...
  4. Create a View. In the "UserController". ...
  5. Execute the application and change the URL as http://localhost:2669/User/Show.
Feb 10, 2021

How to pass data from view to controller in MVC in Spring Boot? ›

That's pretty easy in Spring MVC: Just declare a HttpServletRequest argument in the controller method and use the getParameter() method to retrieve parameter value from URL query string (GET) or from HTML form (POST). Use the spring form tag libs to bind your properties to an object.

How to pass TextBox value from view to controller in MVC using jquery? ›

The value of the TextBox is passed as parameter and the returned response is displayed using JavaScript Alert Message Box.
  1. @model jQuery_AJAX_MVC.Models. PersonModel.
  2. </head>
  3. <body>
  4. $(function () {
  5. type: "POST",
  6. url: "/Home/AjaxMethod",
  7. contentType: "application/json; charset=utf-8",
  8. dataType: "json",
Feb 7, 2017

Top Articles
Latest Posts
Article information

Author: Arielle Torp

Last Updated: 14/09/2023

Views: 6532

Rating: 4 / 5 (61 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Arielle Torp

Birthday: 1997-09-20

Address: 87313 Erdman Vista, North Dustinborough, WA 37563

Phone: +97216742823598

Job: Central Technology Officer

Hobby: Taekwondo, Macrame, Foreign language learning, Kite flying, Cooking, Skiing, Computer programming

Introduction: My name is Arielle Torp, I am a comfortable, kind, zealous, lovely, jolly, colorful, adventurous person who loves writing and wants to share my knowledge and understanding with you.