Is this an obsolete coding method? ASP.Net MVC

I am trying to understand how ASP.NET MVC works, and I was recommended to follow the MVC Music Store Tutorial , however, I am having problems since I use other (more modern) software.

According to this page , I have to add List 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 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 that constantly add genres every time I run the index action method?

+5
source share
2 answers

Your syntax is incorrect. Your first fragment is the initializer of the object and is no different from your second block of code in which you create a new instance of Genre and assign its Name property only in the first case when you try to assign { Name = "Disco" } to new Genre() .

Read more about Object Initializer

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

To answer your second question, yes, this list (which is completely in memory) will be created and then discarded every time your action is executed. This means this is sample code, if your application is more complex, you will probably get lists like this from another place. Also, the code does not seem to do anything with this list, but I assume it is out of the question - you probably want it to be part of a model or viewbag, etc.

+2
source

All Articles