0

This seems to be a very basic question, but I have not been able to find an answer. I'm attempting to define a variable in one of my controller classes in order to take a "DRY" (Don't Repeat Yourself) approach to my [Bind(Include=...)] attribute settings for my action methods.

I'm attempting to do this:

// Make the accessible fields more DRY
List<string> field_access = new List<string>();
field_access.Add("Title");
field_access.Add("Author");
field_access.Add("Genre");
field_access.Add("Level");

...

public ActionResult Create([Bind(Include = field_access)] Song song)

Instead of this:

public ActionResult Create([Bind(Include = "ID,Title,Author,Genre,Level")] Song song)

Here's the error: CS1519 Invalid token '(' in class, struct, or interface member declaration

An guidance would be much appreciated.

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
jkrun2472
  • 5
  • 2
  • In case you are white listing the fields you wish to bind, you might want to consider using a `view model` instead, as [well explained in this answer](https://stackoverflow.com/questions/11064316/what-is-viewmodel-in-mvc) – Lennart Stoop Feb 22 '18 at 21:43
  • Where are the `Title`, `Author`, etc. values coming from? Are they being posted from the client? Are they route values or query string values in the URL? Other? – NightOwl888 Feb 22 '18 at 22:21
  • Thanks @LennartStoop, but my application needs to manage the primary key of table associated with the model since I'm not having that done at the db level. – jkrun2472 Mar 08 '18 at 16:36

1 Answers1

0

The error CS1519 means that you have some invalid token in your code.

You don't need to use a list in this case. You can create a constant in your controller and then use it on the attribute:

public class SongsController : Controller
{
    private const string FieldAccess = "ID,Title,Author,Genre,Level";

    public ActionResult Create([Bind(Include = FieldAccess)] Song song)
    {

    }
}
  • Thanks so much @Fabiano! This solved the problem. I think the problem was where I was declaring the string. I had it outside of my controller class code block and in the namespace area, and the namespace didn't like that at all. With this approach I can declare the list in one place and have over-posting protection when I create and update. One list to manage. Thanks again. – jkrun2472 Mar 08 '18 at 17:02