5

I am trying to understand how ASP.NET MVC works and I have been recommended to follow the MVC Music Store Tutorial, however I am having problems since I am using different (more current) software.

According to this page I should add a List of genres to my action method inside my StoreController.cs. However according to Visual studio, this piece of code seems to be incorrect or not recognized. The error says: Identifier expected;'new' is a keyword. Should I use different code or do this in my model class instead in some way?

public ActionResult Index()
{
   var genres = new List<Genre>
   {
       new Genre = { Name = "Disco" },
       new Genre = { Name = "Jazz" },
       new Genre = { Name = "Rock" }
   };

return View();
}

Shouldn't something like this do the job?:

public ActionResult Index()
{
    //var genres = new List<Genre>
    //{
    //    new Genre = { Name = "Disco" },
    //    new Genre = { Name = "Jazz" },
    //    new Genre = { Name = "Rock" }
    //};

    var genres = new List<Genre>();
    genres.Add(new Genre() { Name = "Disco" });
    genres.Add(new Genre() { Name = "Jazz" });
    genres.Add(new Genre() { Name = "Rock" });

    return View();
}

And doesn't this constantly add the genres everytime I would run through the Index action method?

2 Answers 2

5

Your syntax is incorrect. Your first snippet is an object initializer and is no different than your second block of code where you create a new instance of Genre and assign its Name property, only in the first case you are attempting to assign { Name = "Disco" } to new Genre().

Read more on Object Initializer

public ActionResult Index()
{
    var genres = new List<Genre>
    {
       new Genre { Name = "Disco" },
       new Genre { Name = "Jazz" },
       new Genre { Name = "Rock" }
    };
    return View();
}
1
  • Ah I see what I did wrong, using the "=" symbol in front the brackets.
    – Barrosy
    May 7, 2017 at 15:49
2

To answer your second question, yes, that list (which is entirely in memory) will get created and then discarded every time your action runs. It's only meant to be sample code, if your application is more complicated you will probably get lists like this from somewhere else. Also, the code doesn't seem to do anything with this list, but I assume that's left out - you probably want it as part of the model or viewbag etc.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.