我有这个恼人的问题,我的DropDownlist默认情况下不选择当前值.
控制器:
var YearsCycling = new SelectList(new List<SelectListItem>()
{
new SelectListItem(){ Value="1yr", Text="1yr"},
new SelectListItem(){ Value="1-3yrs", Text="1-3yrs"},
new SelectListItem(){ Value="3-5yrs", Text="3-5yrs"},
new SelectListItem(){ Value="5-10yrs", Text="5-10yrs"},
new SelectListItem(){ Value="10+yrs", Text="10+yrs"}
},
"Value",
"Text",
new SelectListItem() { Value = "5-10yrs", Text = "5-10yrs",
Selected = true });
ViewBag.YearsCycling = YearsCycling;
Run Code Online (Sandbox Code Playgroud)
视图:
<%:Html.DropDownListFor(model=>model.YearsCycling,(SelectList)ViewBag.YearsCycling,"-select-") %>
Run Code Online (Sandbox Code Playgroud)
但它不是选择"5-10yrs",而是显示"-select-"选项,如果我检查DOM源,则不会选择任何元素.
更新:我仍然不知道问题是什么,但我现在通过做一些丑陋的事情让它工作:
<%
var sl = (SelectList)ViewBag.YearsCycling;
%>
<select name="YearsCycling" id="YearsCycling">
<%foreach(var li in sl){ %>
<option value="<%:li.Value %>" <%if(li.Selected){%>selected="true"<%}%>><%:li.Text %></option>
<%} %>
</select>
Run Code Online (Sandbox Code Playgroud)
这不是最好的解决方案,但如果你因为你一直在拉扯你的头发来解决这个问题,这应该会有所帮助.
试试这个:
创建一个viewmodel:
public class MyViewModel
{
public string SelectedValue { get; set; }
public IEnumerable<SelectListItem> YearsCycling { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
控制器:
var YearsCycling = new SelectList(new List<SelectListItem>()
{
new SelectListItem(){ Value="1yr", Text="1yr"},
new SelectListItem(){ Value="1-3yrs", Text="1-3yrs"},
new SelectListItem(){ Value="3-5yrs", Text="3-5yrs"},
new SelectListItem(){ Value="5-10yrs", Text="5-10yrs"},
new SelectListItem(){ Value="10+yrs", Text="10+yrs"}
},
"Value",
"Text");
MyViewModel model = new MyViewModel();
model.YearsCycling = YearsCycling;
model.SelectedValue = "5-10yrs";
return View(model);
Run Code Online (Sandbox Code Playgroud)
视图:
<%:Html.DropDownListFor(model=>model.SelectedValue,(SelectList)Model.YearsCycling) %>
Run Code Online (Sandbox Code Playgroud)
如果您要像这样呈现列表: @Html.DropDownListFor(model => model.EntityID, Model.EntitySelectList)
.NET MVC在渲染选择选项时将使用的值将匹配值model.EntityID.ToString().
......它不会选择 Model.EntitySelectList.SelectedValue
......或任何EntitySelectList.Item.SelectedValue物品.
...换句话说,当渲染DropDownListFor而不是列表本身时,List和List Items的SelectedValue属性将被忽略.
无论设置什么Model.EntitySelectList.SelectedValue或Model.EntitySelectList.Item.SelectedValue,ASP.NET MVC都不会呈现选择.使用model.EntityID来代替.
你的代码应该是。
var YearsCycling = new List<SelectListItem>()
{
new SelectListItem(){ Value="1yr", Text="1yr"},
new SelectListItem(){ Value="1-3yrs", Text="1-3yrs"},
new SelectListItem(){ Value="3-5yrs", Text="3-5yrs"},
new SelectListItem(){ Value="5-10yrs", Text="5-10yrs", Selected=true},
new SelectListItem(){ Value="10+yrs", Text="10+yrs"}
};
ViewBag.YearsCycling = YearsCycling;
Run Code Online (Sandbox Code Playgroud)
您可以改用此重载。
<%:Html.DropDownListFor(model=>model.YearsCycling,ViewBag.YearsCycling as List<SelectListItem>) %>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
23961 次 |
| 最近记录: |