How do you exclude properties from binding when calling UpdateModel()?

后端 未结 4 826
伪装坚强ぢ
伪装坚强ぢ 2020-12-20 11:46

I have a view model sent to the edit action of my controller. The ViewModel contains references to EntityObjects. (yea i\'m fine with it and don\'t need to want to duplicate

4条回答
  •  鱼传尺愫
    2020-12-20 12:11

    Use the Exclude property of the Bind attribute:

    [Bind(Exclude="Id,SomeOtherProperty")]
    public class SimplifiedCompanyViewModel
    {
        public int Id { get; set; }
    
        // ...
    }
    

    This is part of the System.Web.Mvc namespace. It takes a comma-separated list of property names to exclude when binding.

    Also you should consider using TryUpdateModel instead of UpdateModel. You can also just have the default model binder figure it out by passing it as an argument to the constructor:

    public ActionResult Create([Bind(Exclude="Id")]SimplifiedCompanyViewModel model)
    {
        // ...
    }
    

提交回复
热议问题