【发布时间】:2016-02-16 22:09:22
【问题描述】:
我有两个实体:部门和部门类型。 在部门的索引视图中,我显示部门列表,当单击按钮时,会打开一个模式并显示部门的详细信息。
在此模式中,具有部门类型的部门以下拉列表显示。我无法使用我在控制器中设置的值选择此下拉列表。
这是代码,是我正在尝试做的示例代码。 型号:
public class Department
{
public int DepartmentId { get; set; }
public string Name { get; set; }
public DepartmentType DepartmentType { get; set; }
public SelectList DepTypeSelectList { get; set; }
}
public class DepartmentType
{
public int TypeId { get; set; }
public string Description { get; set; }
}
public class DepartmentDBContext : DbContext
{
public DbSet<Department> Departments { get; set; }
public DbSet<DepartmentType> DepartmentType { get; set; }
}
控制器:
public ActionResult Index()
{
var list = new List<Department>();
list.Add(new Department{ DepartmentId = 1, Name = "Department 1", DepartmentType = new DepartmentType{ TypeId = 2, Description = "Type 2"}});
var deptList = new List<DepartmentType>
{
new DepartmentType {TypeId = 1, Description = "Type Desc 1"},
new DepartmentType {TypeId = 2, Description = "Type Desc 2"}
};
var selectList = new SelectList(deptList, "TypeId", "Description", 2);
list[0].DepTypeSelectList = selectList;
ViewBag.TypeId = new SelectList(deptList, "TypeId", "Description");
return View(list);
}
部门的索引视图:
@model IEnumerable<ValidationTest.Models.Department>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th></th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@{
var divName = "#myModal" + item.DepartmentType.TypeId;
}
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="@divName">Open Modal</button>
@Html.Partial("_DepartmentType", item)
</td>
</tr>
}
</table>
部分视图部门类型:
@model ValidationTest.Models.Department
@{
var divName = "myModal" + Model.DepartmentType.TypeId;
}
<!-- Modal -->
<div id="@divName" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Department Type</h4>
</div>
<div class="modal-body">
<p>Type Id: @Model.DepartmentType.TypeId</p>
<p>Description: @Model.DepartmentType.Description</p>
<p>
@Html.DropDownList("TypeId", Model.DepTypeSelectList, "-- Select Type --", new { @class = "form-control input-sm" })
</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
有什么帮助吗? 谢谢
【问题讨论】:
-
请用特定问题更新您的帖子。
-
问题很具体,正如它所说:为什么我无法选择下拉列表。请检查控制器代码: var selectList = new SelectList(deptList, "TypeId", "Description", 2);我正在传递带有选定项目的选择列表,当我打开模型时,未选择组合。另外我贴了一个非常简单易行的代码。
-
您不能使用
foreach循环为集合生成表单控件。您也不能使用部分(您需要使用EditorTemplate),但是为什么要创建多个表单-您只能回发一个-以及您回发到的控制器方法签名是什么。并且您的下拉列表绑定到一个名为TypeId的属性,该属性不存在(尽管您确实有一个名为DepartmentType.TypeId的属性)。