MVC3 dropdownlistfor
Asked Answered
L

3

4

I would like to make a dropdown list, with the numbers 0-10. So users can rate something. At the moment, I have a label: @Html.LabelFor(model=> model.RATE) How can I modify this code that I will have a dropdown box? And that the value of the dropdown box will be stored in model.RATE?

The label is working, but it would be much better to have a dropdown menu.

SOLUTION:

@Html.DropDownListFor(model => model.RATE, Enumerable.Range(0,11).Select( x => new SelectListItem { Text = x.ToString() }));
Lobster answered 22/5, 2012 at 20:22 Comment(0)
Y
4

Just create a list of SelectListItem objects that contain the ratings, and then use Html.DropDownListFor with the rating stored in your model (Model.RATE).

@{
    var ratings = new List<SelectListItem>();
    for( var i = 0; i <= 10; i++ ) {
        days.Add( new SelectListItem { Text = i.ToString(), Value = i.ToString(), Selected = Model.RATE == i } );
    }
}
@Html.DropDownListFor( x => x.RATE, ratings )
Yevette answered 22/5, 2012 at 20:26 Comment(0)
L
4
@Html.DropDownListFor(model => model.RATE, new SelectList(Enumerable.Range(0, 11)))

This will do the data binding to the form and from the form

Leandro answered 22/5, 2012 at 20:25 Comment(6)
0-10 has 11 elements. So Enumerable.Range(0,11).Luella
This doesn't work for me...you can't assign an Enumerable<int> to an Enumerable<SelectListItem>.Yevette
You could use Enumerable.Range(0,11).Select( x => new SelectListItem { Text = x.ToString() } )Yevette
thats true, but SelectList has a constructor for just an Enumerable, so you can just use the constructor to do it for you.Leandro
Thanks, This is working for me: @Html.DropDownListFor(model => model.RATE, Enumerable.Range(0,11).Select( x => new SelectListItem { Text = x.ToString() }));Lobster
how do you add values to the options?Prismatoid
Y
4

Just create a list of SelectListItem objects that contain the ratings, and then use Html.DropDownListFor with the rating stored in your model (Model.RATE).

@{
    var ratings = new List<SelectListItem>();
    for( var i = 0; i <= 10; i++ ) {
        days.Add( new SelectListItem { Text = i.ToString(), Value = i.ToString(), Selected = Model.RATE == i } );
    }
}
@Html.DropDownListFor( x => x.RATE, ratings )
Yevette answered 22/5, 2012 at 20:26 Comment(0)
T
1
@Html.DropDownListFor(m => m.RATE, Model.RateSelectList, "<- Select Option ->")

Model.RateSelectList would be of type IEnumerable<SelectListItem>, m.RATE would be your nullable integer(int?) property. The third parameter would be your default text that would show if m.RATE is null.

Talesman answered 22/5, 2012 at 20:28 Comment(1)
I had no idea how to set a default value until I ran across this. Thanks.Tide

© 2022 - 2024 — McMap. All rights reserved.