Including And Excluding Properties from Model Binding Using Interfaces

Model binding using interfaces 

You can specify distinct interfaces for various sets of characteristics and have your model implement those interfaces if you want to include or omit certain properties from model binding. After that, you can bind your model to that interface type to decide which properties are added when the model is bound.

Here's an example of how you can achieve this.

public interface IIncludeProperties
{
    int Id { get; set; }
    string Name { get; set; }
}
public interface IExcludeProperties
{
    string Address { get; set; }
    string Country { get; set; }
}
public class Mudassar : IIncludeProperties, IExcludeProperties
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public string Country { get; set; }
}

The interfaces "IIncludeProperties" and "IExcludeProperties" are defined in the example above. When modeling binding, each interface represents a set of properties that you want to include or exclude. Both interfaces are implemented by the class "Mudassar".

You may now link your model to the specified interface type in your action method to include or exclude properties.

public class HomeController : Controller
{
    [HttpPost]
    public ActionResult SaveData([Bind(typeof(IIncludeProperties))] Mudassar model)
    {
    
        return RedirectToAction("Index");
    }
}

The [HttpPost] element is used in the example above to decorate the "SaveData" action method so that it may handle a POST request. The [Bind(typeof(IIncludeProperties))] attribute on the "Mudassar" model parameter indicates that only the properties described in the "IIncludeProperties" interface (in this case, "Id" and "Name") should be included during model binding. The properties "Address" and "Country" will be disregarded.

You can choose which set of attributes are included during model binding in various action methods by specifying various interface types in the 'Bind' property.