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.
/// <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);
}
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);
}
发布评论
评论(5)
是的,有:它称为视图模型。视图模型是专门针对给定视图的特定需求而定制的类。
因此,不要
使用:
,其中视图模型仅包含需要绑定的属性。然后您可以在视图模型和模型之间进行映射。可以使用 AutoMapper 简化此映射。
作为最佳实践,我建议您始终在视图中使用视图模型。
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:
use:
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;
我想出了一个非常简单的解决方案。
A very simple solution that I figured out.
作为现有答案的补充,C# 6 可以以更安全的方式排除该属性:
或
As an addition to the existing answers, C# 6 makes it possible to exclude the property in a safer way:
or
正如德斯蒙德所说,我发现删除非常容易使用,而且我还做了一个简单的扩展,可以派上用场,可以忽略多个道具...
您可以在操作方法中像这样使用它:
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...
You can use it like this in your action method: