原因
DropDownList扩展方法
解决
现象
我们的html前端代码:
<td> @Html.DropDownListFor(model => model.QueryModelList[i].FieldTypeMenu, (IList<SelectListItem>)ViewBag.FieldTypeMenu, new { @class = "form-control" }) @Html.ValidationMessageFor(model => model.QueryModelList[i].FieldTypeMenu) </td>
原因
我们初看该段代码,都是调用的MVC sdk原生函数,从写法上确实是没有问题的,但是为什么在界面上显示的不是我们绑定的初始值呢,我们和Web开发平台MVC开源代码联调了一下,发现
DropDownListFor方法确实是不给绑定初始值的,那怎么办?
看来我们用MVC原生方法是不行了,我们只能为DropDownList扩展一个方法,我们为它绑定好初始值。
DropDownList扩展方法
public static class HtmlExtensionsF { public static MvcHtmlString DropDownListHelperFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, object selectedValue, string optionLabel, object htmlAttributes) { foreach (var item in selectList) { var text = item.Text; if (hasSelectedItem(item, selectedValue)) item.Selected = true; } if (string.IsNullOrEmpty(optionLabel)) { return htmlHelper.DropDownListFor(expression, selectList, "", htmlAttributes); } else { return htmlHelper.DropDownListFor(expression, selectList, htmlAttributes); } } private static Func<SelectListItem, object, bool> hasSelectedItem = (selectedItem, selectedValue) => { if (selectedValue != null) { var selectedValueString = Convert.ToString(selectedValue); if (!string.IsNullOrWhiteSpace(selectedValueString)) { return string.Equals(selectedValueString, selectedItem.Value, StringComparison.CurrentCultureIgnoreCase); } } return false; }; }
解决
<td> @Html.DropDownListHelperFor(model => model.QueryModelList[i].FieldTypeMenu, (IList<SelectListItem>)ViewBag.FieldTypeMenu, Model.QueryModelList[i].FieldTypeMenu,null, new { @class = "form-control" }) @Html.ValidationMessageFor(model => model.QueryModelList[i].FieldTypeMenu) </td>
我们调用我们写的扩展方法DropDownListHelperFor,如下图可以看到我们的结果已经呈现出我们想要的,细心的同学应该可以看到我们扩展方法里有一段这样的代码
if (hasSelectedItem(item, selectedValue)) item.Selected = true;,对的,这个是我们绑定初始值的关键代码。
