ASP.NET MVC - [Bind(Exclude =“Id”)的替代方案]

时间:2011-01-07 22:50:28

标签: c# asp.net-mvc-2 modelbinders

[Bind(Exclude = "Id")]Related Question)

是否有其他选择?

我可以写一个模型绑定器吗?

5 个答案:

答案 0 :(得分:31)

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

所以而不是:

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

使用:

public ActionResult Index(SomeViewModel viewModel)

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

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

答案 1 :(得分:13)

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

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

    if (ModelState.IsValid)
       {
           //Save Changes;
       }
    }
}

答案 2 :(得分:11)

您可以使用;

直接使用属性排除属性
[BindNever]

答案 3 :(得分:6)

作为现有答案的补充,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)

答案 4 :(得分:3)

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

    /// <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);
    }

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

    ModelState.Remove(nameof(obj.ID), nameof(obj.Prop2), nameof(obj.Prop3), nameof(obj.Etc));