1

I am quite new to MVC, I have created Model, View and a Controller for the following Model

public class Student:Basic
{
    public Guid StudentId { get; set; }
    public string Name { get; set; }
    [ForeignKey("SchoolClass")]
    public virtual Guid StudentClassId { get; set; }
    public virtual SchoolClass SchoolClass { get; set; }
}

Here in the View I wanted to have a DropDownList for Class. But I am not sure how can I achieve it without using View-Model. Many solutions ask me to create a View-Model with SelectList for Class and populate the Class (get all class in DB) in Controller then use this in View. Is this the only option here? Or can we populate the DropDown with any other way?

Joe 89
  • 850
  • 1
  • 12
  • 30
  • 4
    You could assign the `SelectList` to a `ViewBag` property, but using a view model is recommended and has numerous other advantages - refer [What is ViewModel in MVC?](http://stackoverflow.com/questions/11064316/what-is-viewmodel-in-mvc) –  Aug 16 '15 at 09:39
  • in this case the `ViewBag` is just part of the view model ;) - of course you can *spaghetti code* everything in the view as well ... no really: **don't** – Random Dev Aug 16 '15 at 09:40
  • You can pass anything to a strongly typed View - this means that you can pass a Model directly. Or you can pass anything through the dynamic ViewBag. However, both approaches can very soon become impractical and, to solve their problems, in the you'll probably resort to a ViewModel anyway. – Theodoros Chatzigiannakis Aug 16 '15 at 10:03

1 Answers1

1

It's not necessary to use model for passing select list options to the view. You can populate your select list in Razor like that:

@{
   var listItems = new List<SelectListItem>();
   listItems.Add(new SelectListItem
   {
      Text = "Item 1",
      Value = "Item 1"
   });
   listItems.Add(new SelectListItem
   {
      Text = "Item 2",
      Value = "Item 2",
      Selected = true
   });
}

@Html.DropDownListFor(model => model.MyValue, listItems, "-- Please choose --")

Or you can always have some helper class with static method that returns List<SelectListItem>:

@Html.DropDownListFor(model => model.MyValue, SelectListHelper.GetOptions())
Andrei
  • 42,814
  • 35
  • 154
  • 218
  • But what if I wanted to populate the DropDownList values from controller? I believe we can do that Ajax calls but I think that will be little too complicated than having a ViewModel! – Joe 89 Aug 16 '15 at 14:43
  • @MohanPrasath If I want to populate DropDown from the controller, I would use ViewBag or Model for this – Andrei Aug 16 '15 at 17:17