在使用@Html.DropDownList的过程中,发现它的用法很局限,比如在加载的时候显示设定的默认项或者调整它的显示样式,在网上查了一些资料,终于把这个问题解决了。
一、View代码
- @using (Ajax.BeginForm("Edit", new AjaxOptions() { OnSuccess = "afterEdit" }))
- {
- @Html.HiddenFor(model => model.ID)
- @Html.HiddenFor(model => model.isUsed)
- <div style="padding: 40px 40px 30px 50px;">
- <table style="font-size:12px" align="center">
- <tr>
- <td>@Html.Label("评论人职务:")</td>
- <td>@Html.DropDownList("YzPositionCriticsID", ViewData["CriticsPositionType"] as SelectList)</td>
- </tr>
- <tr>
- <td>@Html.Label("被评论人职务:")</td>
- <td>@Html.DropDownList("YzPositionEvaluationID", ViewData["EvaluationPosition"] as SelectList)</td>
- </tr>
- <tr>
- <td>@Html.Label("权重:")</td>
- <td>@Html.TextBoxFor(model => model.Weight)</td>
- </tr>
- </table>
- </div>
- }
二、Controller代码
- public ActionResult Edit(string id)
- {
- //6.1根据ID从数据库中查出要修改的相关数据
- Guid Gid = new Guid(id);
- Model.DTO.YzWeightEntityDTO weight = weightBLL.LoadEnities(u => u.ID == Gid).FirstOrDefault().ToDto();
- //6.2查询YzPositionEntity实体的数据
- List<Model.DTO.YzPositionEntityDTO> positionList = positionBLL.LoadEnities().ToList().Select(s => s.ToDto()).ToList();
- //6.3将YzPositionEntity的数据封装到 SelectList中,制定要生成下拉框选项的value和text属性
- SelectList selList1 = new SelectList(positionList, "ID", "PositionType", weight.YzPositionCriticsID);
- SelectList selList2 = new SelectList(positionList, "ID", "PositionType",weight.YzPositionEvaluationID);
- //6.4把生成的集合放到ViewData中
- ViewData["CriticsPositionType"] = selList1;
- ViewData["EvaluationPosition"] = selList2;
- return View(weight);
- }
在这里需要注意的是:SelectList selList1 = new SelectList(list,"","",***),这里的***就是下拉框加载时候要显示的默认值。
最后的显示效果如下: