Guerrilla
Guerrilla

Reputation: 14856

Setting private property on ViewModel

I have followed this tutorial for creating drop downs in ASP.NET MVC: http://odetocode.com/blogs/scott/archive/2013/03/11/dropdownlistfor-with-asp-net-mvc.aspx

The code sample given is:

public class IceCreamFlavor
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class ViewModel
{
    private readonly List<IceCreamFlavor> _flavors;

    [Display(Name = "Favorite Flavor")]
    public int SelectedFlavorId { get; set; }

    public IEnumerable<SelectListItem> FlavorItems
    {
        get { return new SelectList(_flavors, "Id", "Name");}
    }
}

What is the proper way to set _flavors? It is private readonly. Is there any reason for this? Some feature of MVC to populate it?

I can obviously make it public or private with a constructor but I am wondering why Scott Allen set it this way. Is there some logic to it?

Upvotes: 0

Views: 775

Answers (1)

mm8
mm8

Reputation: 169200

What is the proper way to set _flavors?

You can set it to any List<IceCreamFlavor> you want based on your custom logic in the constructor of the view model.

The readonly modifier means that any assignments to the field must occur as part of the declaration or in a constructor in the same class: https://msdn.microsoft.com/en-us/library/acdd6hb7.aspx.

So you cannot set this field from anywhere else than in the constructor of the ViewModel class. The part of initializing the list has obviously been omitted from the example ("assuming the _flavors field is populated with real ice cream flavors from a database or elsewhere") but the view model class is supposed to create the List<IceCreamFlavor> in its constructor and then simply expose an IEnumerable<SelectListItem> that the view can bind to. The outside world only knows about the IEnumerable . Only the view model class itself knows about the private _flavors field.

Upvotes: 1

Related Questions