0

I am using the MVC Bind attribute as followed to include only specific fileds (properties) in MVC Model binding and it works very good:

[Bind(Include = "FirstName,LastName")]
    public class MyClass
    {        
        [Required]
        public string FirstName { get; set; }
        [Requiered]
        public string LastName{ get; set; }
        public string Discreet{ get; set; }
     }

But i prefer to use it in the same way of the Required attribute instead of declare the fields i want to include at the top of the class name.

Is there an option to achieve that?

[NeverBind] doesn't work for me for some reason and in any case i prefer to specify the fields to include rather than the fields to exclude.

Omtechguy
  • 3,321
  • 7
  • 37
  • 71
  • 1
    Short answer - No. - the `BindAttribute` is decorated with `[AttributeUsageAttribute(AttributeTargets.Class | AttributeTargets.Parameter` which means it cannot be applied to a property. BUt you should be using a view model any way, not data models in a view, so a `[Bind]` should never be required –  Apr 23 '18 at 08:35
  • [Stop using Bind](https://cpratt.co/stop-using-bind/) –  Apr 23 '18 at 08:37
  • @Stephen Muecke, if i have only few differences between my data models and the view model i don't see any reason to manage two classes, duplicate the fields and manage mappings. – Omtechguy Apr 23 '18 at 08:38
  • 1
    That is no excuse for bad practice :) –  Apr 23 '18 at 08:39
  • Agreed, and there are shortcuts to handling the mappings using tools such as AutoMapper, which will take 95% of the tedium and code away from that. – ADyson Apr 23 '18 at 09:39

0 Answers0