ASP.NET MVC - Alternative for [Bind(Exclude = “Id”)]

亡梦爱人 提交于 2019-12-28 05:22:08

问题


Is there an alternative for [Bind(Exclude = "Id")] (Related Question) ?

Could I write a model binder?


回答1:


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.




回答2:


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



回答3:


You can exclude properties directly with an attribute using;

[BindNever]



回答4:


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)



回答5:


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


来源:https://stackoverflow.com/questions/4631000/asp-net-mvc-alternative-for-bindexclude-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!