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

前端 未结 5 2166
执笔经年
执笔经年 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:28

    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...

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

    You can use it like this in your action method:

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

提交回复
热议问题