c# – 使用默认值从SelectList创建DropDownListFor
发布时间:2020-12-15 18:23:28 所属栏目:百科 来源:网络整理
导读:我有一个下拉列表: @Html.DropDownListFor(model = model.Item.Item.Status,new SelectList(@Model.AllStatus,"id","Description"),new { id = "statusDropdown" }) @Html.ValidationMessageFor(model = model.Item.Item.Status) HTML输出: select id="sta
我有一个下拉列表:
@Html.DropDownListFor(model => model.Item.Item.Status,new SelectList(@Model.AllStatus,"id","Description"),new { id = "statusDropdown" }) @Html.ValidationMessageFor(model => model.Item.Item.Status) HTML输出: <select id="statusDropdown" class="valid" name="Item.Item.Status" data-val-required="The Status field is required." data-val-number="The field Status must be a number." data-val="true"> <option value="2">Completed by Admin</option> <option value="3">General Error</option> <option value="4">New</option> </select> 如何更新此代码以设置默认选定选项?例如. < option value =“4”selected> New< / option> 我试过了: @Html.DropDownListFor(model => model.Item.Item.Status,"Description",@Model.SelectedStatusIndex),new { id = "statusDropdown" }) @ Model.SelectedStatusIndex的值为4,但不会将默认选项更改为New. 我也尝试过: @Html.DropDownListFor(model => model.SelectedStatusIndex,new { id = "statusDropdown" }) @Html.ValidationMessageFor(model => model.Item.Item.Status) 这将选择默认选项“New”,但不会通过HTTP POST下拉列表设置model.Item.Item.Status. 其他细节: model.Item.Item.Status是一个int. @ Model.AllStatus是一个SQL表,列出了所有可用的状态选项. 解决方法
已经存在关于该
here或
there的一些讨论.其中一个问题可能是使用与字符串不同的类型作为键值.我过去遇到过类似的问题,我知道我像
this一样解决了它 – 在准备列表时明确设置了Selected属性(在你的情况下,AlLStatus).
对于你的情况(在控制器动作中)意味着: IEnumerable<SelectListItem> selectList = from s in allStatus // where ever you get this from,database etc. select new SelectListItem { Selected = (s.id == model.Item.Item.Status),Text = cs.Description,Value = s.id.ToString() }; model.AllStatus = selectList; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |