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

前端 未结 5 2177
执笔经年
执笔经年 2020-12-05 00:42

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

Could I write a model binder?

5条回答
  •  无人及你
    2020-12-05 01:33

    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.

提交回复
热议问题