问题
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() }));
回答1:
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 )
回答2:
@Html.DropDownListFor(model => model.RATE, new SelectList(Enumerable.Range(0, 11)))
This will do the data binding to the form and from the form
回答3:
@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.
来源:https://stackoverflow.com/questions/10709588/mvc3-dropdownlistfor