How to add new option to drop down list in MVC Razor View?
I have 2 dropdown lists in MVC 3 razor view like this:
@Html.DropDownListFor(m => m.UserGroups, Model.UserGroups.Select(x => new SelectListItem() { Text = x.Name, Value = x.Id }), new { @class="pad5" })
They work fine. I have 3 changes to make -
1) First one needs a new option to be added at the top of this list.
<option value="">--pick--</option>
2) And the second one needs to select a specific option upon load. Say I want to pre-select this option on my second list.
<option value="100">My Friends</option>
3) both dropdowns have same data source. This causing both list to have same name on the form. How do I change the name?
I am able 开发者_Python百科to change the id, but the name seems not changing if I add this to the end:
new { @id="ViewGroup", @name="ViewGroup"}
If you have a viewmodel created, you can simply do for each dropdown:
@model Namespace.myViewModel
<select id="dropdownOne" name="dropdownOne">
<option value="">--pick--</option>
@foreach (var item in Model.myModel)
{
if(@item.id==100) {
<option value="@item.id" selected="selected">@item.Name</option>
}
else {
<option value="@item.id>@item.Name</option>
}
}
</select>
精彩评论