ASP.NET MVC –

是否有[Bind(Exclude = "Id")] ( 相关问题)的替代方案?

我能写一个模型活页夹吗?

是的,它有:它被称为视图模型。 视图模型是专门针对给定视图的特定需求而定制的类。

所以代替:

 public ActionResult Index([Bind(Exclude = "Id")] SomeDomainModel model) 

使用:

 public ActionResult Index(SomeViewModel viewModel) 

其中视图模型仅包含需要绑定的属性。 然后,您可以在视图模型和模型之间进行映射。 使用AutoMapper可以简化此映射。

作为最佳实践,我建议您始终在视图中使用视图模型。

我想出了一个非常简单的解决方案。

 public ActionResult Edit(Person person) { ModelState.Remove("Id"); // This will remove the key if (ModelState.IsValid) { //Save Changes; } } } 

您可以使用以下属性直接排除属性;

 [BindNever] 

作为对现有答案的补充,C#6使得以更安全的方式排除财产成为可能:

 public ActionResult Edit(Person person) { ModelState.Remove(nameof(Person.Id)); if (ModelState.IsValid) { //Save Changes; } } } 

要么

 public ActionResult Index([Bind(Exclude = nameof(SomeDomainModel.Id))] SomeDomainModel model) 

正如Desmond所说,我发现删除非常容易使用,我也做了一个简单的扩展,可以派上用场,让多个道具被忽略……

  ///  /// Excludes the list of model properties from model validation. ///  /// The model state dictionary which holds the state of model data being interpreted. /// A string array of delimited string property names of the model to be excluded from the model state validation. public static void Remove(this ModelStateDictionary ModelState, params string[] modelProperties) { foreach (var prop in modelProperties) ModelState.Remove(prop); } 

你可以在你的动作方法中使用它:

  ModelState.Remove("ID", "Prop2", "Prop3", "Etc");