In this Video, I am going to discuss Including and Excluding Properties from Model Binding using Interface in ASP.NET MVC Application. Please watch our previous Video before proceeding to this Video where we discussed How to include and Exclude Properties using Bind Attributein ASP.NET MVC Application. This is also a continuation part of our previous Video. Here, I will show you how to include and exclude properties in Model Binding using Interface.
Include and Exclude Properties from Model Binding using Interface
First Create an interface “IEmployee” as shown below.
Notice that the above IEmployee interface has got only the properties that we want to include in model binding. The “Name” property is not present. This means “Name” property will be excluded from model binding. So, modify the “Employee.cs” class file in the “BusinessLayer” project as shown below.
Next, Modify the “Edit_Post()” action method of EmployeeController as shown below.
Notice that we are explicitly calling the model binder by calling UpdateModel() function passing our interface IEmployee. The model binder will update only the properties that are present in the interface. So if you were generating a post request using fiddler as we did in the previous session “Name” property of the “Employee” object will not be updated.
So, in short, there are several ways to Include and Exclude properties from Model Binding in ASP.NET MVC Application. Depending on the architecture and requirements of your project you need to choose the approach that best fits your needs.