Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC3 dropdownlistfor

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() }));
like image 942
1408786user Avatar asked Jan 17 '23 14:01

1408786user


1 Answers

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 )
like image 183
Ethan Brown Avatar answered Jan 25 '23 02:01

Ethan Brown