Eric
Eric

Reputation: 2293

mvc dropdown binding for an int in razor view

I have a domain/entity object with an integer:

public Int32 HoursToWait {get;set;}

I put the same thing in my view model:

public Int32 HoursToWait {get;set;}

<select id="HoursToWait" name="HoursToWait">
    <option value="1">1</option>
    <option value="6">6</option>
    <option value="12" selected="selected">12</option>
    <option value="12">24</option>
    <option value="12">36</option>
    <option value="12">48</option>
    <option value="12">72</option>
</select>

The crux of the issue is that my entity model is an integer. I'd like to display it as a drop down, to only allow certain hours to be selected. And, once selected, I'd like to default it the next time it's displayed.

The above code "works", but it's hard coded to default to 12 so it's corny and if the user changes the HoursToWait value, when reloaded it just goes back to 12.

So primarily question would be what sort of view model property and razor elements should I use to handle this?

Upvotes: 4

Views: 9942

Answers (2)

David Silva-Barrera
David Silva-Barrera

Reputation: 1146

Using ViewBag will work too:

You have the property HoursToWait in your ViewModel.

public class MyViewModel
{
  public int HoursToWait { get; set;}
}

...and in the Controller's GET method:

var Values = new List<int> { 1, 6, 12, 24, 36, 48, 72};
var aList = Values.Select((x, i) => new { Value = (x < 12 ? x : 12), Data = x }).ToList();
ViewBag.HoursList = new SelectList(aList, "Value", "Data");
//The example also shows how to define both value and data for each item 

And in the View:

@model MyViewModel
@using (Html.BeginForm())
{
  @Html.DropDownListFor(m => m.HoursToWait, (SelectList)ViewBag.HoursList, "-select-")
}

Upvotes: 1

user3559349
user3559349

Reputation:

Your view model would contain properties for HoursToWait and a SelectList for selecting the values. Note I assume you have typos in the html and that the option values should match the text (currently you have 5 options with value="12")

public class MyViewModel
{

  public int HoursToWait { get; set;}
  public SelectList HoursToWaitList { get; set; }
}

and in the controllers GET method

List<int> hours = new List<int>{ 1, 6, 12, 24, 36, 48, 72 };
MyViewModel model = new MyViewModel()
{
  HoursToWait = 12, // set the default selection (based on the existing value in the db)
  HoursToWaitList = new SelectList(hours);
}

And in the view

@model MyViewModel
@using (Html.BeginForm())
{
  @Html.DropDownListFor(m => m.HoursToWait, Model.HoursToWaitList, "-Please select-")
  <input type="submit" ... />
}

Upvotes: 6

Related Questions