两个@Html的级联更新.DropDownListFor在MVC4与模型绑定

本文关键字:MVC4 模型 绑定 DropDownListFor @Html 级联 更新 两个 | 更新日期: 2023-09-27 18:16:21

我看到了这个,但是我有一个不同的Q.我有一个这样的视图:

@model myPrj.Models.RollCallModel
...
<table>
    <tr> //Master DDL
       <td>
          @Html.LabelFor(model => model.CourseID) 
          @Html.DropDownListFor(model => model.CourseID,
            new SelectList(new myPrj.Models.myDbContext().Courses
               .Where(c => c.StatusID == 0), "ID", "ID"), 
            "choose...", new { id = "ddlCourse"})
          @Html.ValidationMessageFor(model => model.CourseID)
       </td>
     </tr>
     <tr> //Detail DDL
        <td>
            @Html.LabelFor(model => model.PersonnelID) 
            @Html.DropDownListFor(model => model.PersonnelID,
                 null, "choose another...", new { id = "ddlPersonnel"})
            @Html.ValidationMessageFor(model => model.PersonnelID)
        </td>
     </tr>
</table>
...

我对jquery的级联更新有足够的了解。我的问题是,是否有可能在不需要为Detail DDL编写<option>something</option>迭代的情况下对这些DDL执行级联更新?如果没有,最方便的替代方案是什么?

注:事实上,由于模型绑定的惯例,我试图用html helper呈现详细的DDL。如果我别无选择,只能通过<select id=""></select>渲染它,我如何将这个select元素绑定到模型?

谢谢

更新:似乎没有办法…

两个@Html的级联更新.DropDownListFor在MVC4与模型绑定

是啊!当然有:详情请参阅此。但是,它需要一个额外的操作方法和每个Detail DDL的部分视图。

最后我喜欢决定通过JQuery并在JsonResult上逐级添加<options>

要在MVC中填充下拉列表,请在视图中使用此选项:

@Html.DropDownListFor(model => model.CourseID, new SelectList((IList<SelectListItem>)ViewData["MyCourse"],
                                            "Value", "Text"), new { @class = "span5" })

支持View,你应该在相应的控制器动作中写下面的代码:

public ActionResult RoleList(int id)
{
     ViewData["MyCourse"] = FillCourseList(id);
     CourseModel model = new CourseModel();
     model.courseid= id;
     return View(model);
}

要填充ViewData,你需要在同一个控制器中有一个相应的函数,如下所示:

public IList<SelectListItem> FillCourseList(int id)
        {
            List<master_tasks> lst = new List<master_tasks>();
            lst = _taskInterface.getMasterTasks();
            IList<SelectListItem> items = new List<SelectListItem>();
            items.Add(new SelectListItem
                {
                    Text = "Select Task",
                    Value = "0"
                });
            for (int i = 0; i < lst.Count; i++)
            {
                items.Add(new SelectListItem
                {
                    Text = lst[i].code + " - " + lst[i].name,
                    Value = lst[i].id.ToString()
                });
            }
            return items;
        }

IList是一个泛型列表,其列表项为Html类型。