One way to solve this problem using centralized code is to override BindModel
of DefaultModelBinder
and exclude the properties which you don't want to bind.
public class CustomDataBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
if (bindingContext.ModelType == typeof(BusinessModel))
{
HttpRequestBase request = controllerContext.HttpContext.Request;
string name = request.Form.Get("Name");
return new BusinessModel
{
Name = name
};
}
else
{
return base.BindModel(controllerContext, bindingContext);
}
}
}
And then register it at Global.asax
in Application_Start()
.
ModelBinders.Binders.Add(typeof(BusinessModel), new CustomDataBinder());
In above case I have used BusinessModel
as described as below -
public class BusinessModel
{
public string prop1 { get; set; }
public string Name { get; set; }
}
To test, I have created a simple view -
@model WebApplication1.Controllers.BusinessModel
@using (Html.BeginForm("PostData", "Home"))
{
@Html.EditorFor(model => model.prop1, new { htmlAttributes = new { @class = "form-control" } })
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
<input type="submit" value="Create" class="btn btn-default" />
}
When view renders, I entered some data in both the editors -

When I hit create button, the entered value in Prop1
editor was not binded -
