Reputation: 133
I am creating an ASP.NET MVC 3 application which references a database and within the Edit.cshtml file I wish to limit the edit function of one of the items (Score) to simply be either 0,1,2,3,4. I have tried the options in this post Converting HTML.EditorFor into a drop down (html.dropdownfor?) but cannot seem to get it working.
<div class="editor-label">
@Html.LabelFor(model => model.Score)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Score, "YesNoDropDown")
@Html.ValidationMessageFor(model => model.Score)
</div>
Many thanks.
Chri3
Upvotes: 1
Views: 4723
Reputation: 522
to use Html.DropDownListFor, you need to pass in the argument of type IEnumerable<SelectListItem>
.
Here i've created some mockup for you
in Model
public class SampleModel
{
public string SeletectRateItem { get; set; }
public IList<SelectListItem> RateItem
{
get
{
var item = new List<SelectListItem>();
item.Add(new SelectListItem(){Selected = false, Text = "1", Value = "1"});
item.Add(new SelectListItem(){Selected = false, Text = "2", Value = "2"});
item.Add(new SelectListItem(){Selected = false, Text = "3", Value = "3"});
item.Add(new SelectListItem(){Selected = false, Text = "4", Value = "4"});
item.Add(new SelectListItem(){Selected = false, Text = "5", Value = "5"});
return item;
}
}
}
and in cshtml
@Html.DropDownListFor(m => m.SeletectRateItem, Model.RateItem)
Upvotes: 1
Reputation: 3818
If you don't forsee it needing to be changed often, I'd just use a static select like below:
<div class="editor-label">
@Html.LabelFor(model => model.Score)
</div>
<div class="editor-field">
<select id="score" name="score">
@for(int i=0; i<5; i++){
<option value="@i" @(Model.Score==i ? " selected": "")>@i</option>
}
</select>
</div>
Upvotes: 2