1

I'm trying to pass a bind array instead of defining in the parameters. For example, this code:

    [HttpPost]
    [Route("Create")]
    public ResultsItem Create([Bind(nameof(Person.Username), nameof(Person.Password))] Person)
    {
        ...
    }

It works fine, however, if it gets big, I'll have a big bind list. I wanted to define it in the class instead like below:

Person.cs

public static readonly string[] BindInclude = new[] { nameof(Username), nameof(Password) };
public ResultsItem Create([Bind(Person.BindInclude)] Person newUser)

However, I am getting the following error: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type.

I understand the error, however I'm wondering does anyone have a good way for doing this? Let's say I have a big class, however, I only want to bind like 6 - 10 properties. How can I do this without flooding the Bind[()] in controller.

FerX32
  • 1,407
  • 3
  • 18
  • 28
  • 1
    Use a view model. – Shyju May 11 '18 at 18:20
  • Yea, not but what I was looking for in this case. It's a Web API. We post data (a big single class), and that class gets saved to the db. We only want to bind few properties, not all. – FerX32 May 11 '18 at 18:31
  • View model is the best solution to avoid over posting. – Shyju May 11 '18 at 18:38
  • So basically have a VM like PersonVM, which has like only few properties like Username, Password, and Email. Once we bind the VM, assign them to Person like Person.Username = PersonVM.Username? Is that what you meant? – FerX32 May 11 '18 at 22:47
  • Yes. That is correct. – Shyju May 11 '18 at 22:52
  • [What is ViewModel in MVC?](https://stackoverflow.com/questions/11064316/what-is-viewmodel-in-mvc) –  May 11 '18 at 23:49
  • @StephenMuecke lol, I know what a ViewModel is. However, the concern was different. I guess there's no way to accomplish what's being asked. I'll look into different scenario (whether it be using VM or some other binding tactic). – FerX32 May 12 '18 at 01:02
  • lol - if you know what it is, and why they are used, then you would never be using a data model in a view in the first place, and never be using a `[Bind]` attribute –  May 12 '18 at 01:04
  • 2
    Okay then tell me why [Bind] exist. Benefit of `[Bind] Person`, the object you get back is already populated the way you want it to be. You wont need to convert it again like `Person.Name = PersonVM.Name`. And like I said, this is a Web API, there is no view or anything. This method is simple POST & Save to db. – FerX32 May 12 '18 at 01:18

0 Answers0