Blog Post

Binding properties into controller actions and binding specific properties

Thursday, June 2, 2016 1:45 AM

Binding data from form is straight forward.

We can simply bind the property based on name

public ActionResult Edit(string name)


This works when you have small number of elements.

It does not scale for bigger forms where there are multiple elements we want to pass into controller. After all we using MVC (Model View Controller) which is passing model between view and controller.

Mvc diagram how mvc work

Mvc diagram how mvc work

Lets have a look on some examples of model binding.


You should use a view model which contains only the properties that you want to be edited:

public class EditStudentViewModel
    public string Name { get; set; }

and then we bind the model as follows

public ActionResult Edit(StudentViewModel student)

Finaly we look on selective model binding

Selective model binding is bit more complex, where we take model we have defined in previous step and specify the way we want to bind. 

The binding options we have are

  • Exclude
  • Include



The difference is we have a model and we exclude specific properties. I do not recommend of using this options for simple reason. When the model is being updated and new fields are being added, the exclusion is usually not updated especially when model is reused on multiple places.


public ActionResult Edit([Bind(Exclude = "Id,Birthday")]Student student)



I personally prefer this solution of manually selecting the fields that I want to bind to the model as it defines only the properties that are being binded into the model.



Also I should say, if you do not read the action method properly when you are using this solution you might spend some time wondering why the property is not being binded correctly (my own experience, this was due to renaming property but not the string in include)


public ActionResult Edit([Bind(Include = "Name")]Student student)

How many arguments should arguments should I bind before using model class?

Using normal screen size on get/post actions I am using following

  1. parameters that fit into one line without scrolling can be as parameters

    1-1. if anyone is adding new items they might need to convert to model

  2. model is used if there is more parameters

    2-1. When binding model define items to bind form the model. You should bind only what you need, otherwise the user can send more than you expected.

Error pages
Links and tools