DropDownListFor
HTML帮助程序,使用枚举,如:
@Html.DropDownListFor(model => model.Title, Enum.GetValues(typeof(ICS_Signup_Form.Models.Titles)).Cast<ICS_Signup_Form.Models.Titles>().Select(x => new SelectListItem { Text = x.ToString().ToFriendlyString(), Value = x.ToString() }), new { @class = "styled" })
我的枚举如下:public enum Titles { Mr, Dr, Miss, Mrs, Ms, Other };
如果Model.Title
等于“其他”,则下拉列表不会选择此值,HTML中没有selected="selected"
。我尝试将属性Selected
添加到SelectListItem
:Selected = (x.ToString() == Model.Title)
,当我按照预期逐步执行代码时表达式正常工作,但所选值始终为“Mr”(列表中的第一个)。
甚至更奇怪的是这种方法非常好(就像我项目中的其他7个下拉框一样):
@Html.DropDownListFor(model => model.BusinessStatus, Enum.GetValues(typeof(ICS_Signup_Form.Models.BusinessTypes)).Cast<ICS_Signup_Form.Models.BusinessTypes>().Select(x => new SelectListItem { Text = x.ToString().ToFriendlyString(), Value = x.ToString() }), new { @class = "styled" })
使用枚举:public enum BusinessTypes { Charity, Government, Limited, LLP, Partnership, PLC, SoleTrader };
区别?没有..有什么想法吗?
答案 0 :(得分:3)
tldr; 将DropDownList的名称更改为其他名称
我遇到了同样的问题(虽然在ASPX引擎中,我认为在这种情况下没有任何区别)。以下是 repro 的方法:
代码隐藏(注意第二项中的“Selected = true”):
List<SelectListItem> teams = new List<SelectListItem>();
teams.Add(new SelectListItem { Text = "Slackers", Selected = false, Value = "0" });
teams.Add(new SelectListItem { Text = "Workers", Selected = true, Value = "1" });
ViewData["teams"] = teams;
ASPX代码:
<%: Html.DropDownList("team", (IEnumerable<SelectListItem>)ViewData["teams"]) %>
它重复:你可以看到第一个项目被自动选中,而且这两个项目都没有HTML中的“选中”选项。这是生成的HTML重新编写它:
<select id="team" name="team">
<option value="0">Slackers</option>
<option value="1">Workers</option>
</select>
解决方案:关闭一些元素名称会导致ASPX渲染引擎的行为不同。在我的例子中,我只是将DropDownList名称从“team”更改为“defaultteam” - 它开始工作:
这是 WORKING ASPX代码:
<%: Html.DropDownList("defaultteam", (IEnumerable<SelectListItem>)ViewData["teams"]) %>
,这是由它生成的HTML:
<select id="defaultteam" name="defaultteam">
<option value="0">Slackers</option>
<option selected="selected" value="1">Workers</option>
</select>
答案 1 :(得分:1)
很奇怪。我无法复制。这是我的工作代码。
型号:
public enum Titles { Mr, Dr, Miss, Mrs, Ms, Other };
public class MyViewModel
{
public Titles Title { get; set; }
}
控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
Title = Titles.Other
};
return View(model);
}
}
查看:
@model MyViewModel
@Html.DropDownListFor(
model => model.Title,
Enum.GetValues(typeof(Titles))
.Cast<Titles>()
.Select(x => new SelectListItem
{
Text = x.ToString(),
Value = x.ToString()
}),
new { @class = "styled" }
)
正如所料,Other
已预先选定:
<select class="styled" id="Title" name="Title">
<option value="Mr">Mr</option>
<option value="Dr">Dr</option>
<option value="Miss">Miss</option>
<option value="Mrs">Mrs</option>
<option value="Ms">Ms</option>
<option selected="selected" value="Other">Other</option>
</select>
您可能还会发现following extension method有用。