Is there an alternative for [Bind(Exclude = "Id")]
(Related Question) ?
Could I write a model binder?
Is there an alternative for [Bind(Exclude = "Id")]
(Related Question) ?
Could I write a model binder?
Yes there is: it's called view models. View models are classes which are specifically tailored to the specific needs of a given view.
So instead of:
public ActionResult Index([Bind(Exclude = "Id")] SomeDomainModel model)
use:
public ActionResult Index(SomeViewModel viewModel)
where the view model contains only the properties which need to be bound. Then you could map between the view model and the model. This mapping could be simplified with AutoMapper.
As best practice I would recommend you to always use view models to and from a view.
You can exclude properties directly with an attribute using;
[BindNever]
A very simple solution that I figured out.
public ActionResult Edit(Person person)
{
ModelState.Remove("Id"); // This will remove the key
if (ModelState.IsValid)
{
//Save Changes;
}
}
}
As an addition to the existing answers, C# 6 makes it possible to exclude the property in a safer way:
public ActionResult Edit(Person person)
{
ModelState.Remove(nameof(Person.Id));
if (ModelState.IsValid)
{
//Save Changes;
}
}
}
or
public ActionResult Index([Bind(Exclude = nameof(SomeDomainModel.Id))] SomeDomainModel model)
As Desmond stated, I find remove very easy to use, also I've made a simple extension which can come in handy for multiple props to be ignored...
/// <summary>
/// Excludes the list of model properties from model validation.
/// </summary>
/// <param name="ModelState">The model state dictionary which holds the state of model data being interpreted.</param>
/// <param name="modelProperties">A string array of delimited string property names of the model to be excluded from the model state validation.</param>
public static void Remove(this ModelStateDictionary ModelState, params string[] modelProperties)
{
foreach (var prop in modelProperties)
ModelState.Remove(prop);
}
You can use it like this in your action method:
ModelState.Remove(nameof(obj.ID), nameof(obj.Prop2), nameof(obj.Prop3), nameof(obj.Etc));
© 2022 - 2024 — McMap. All rights reserved.