我有以下代码:
public class OrganisationController : Controller
{
//
// GET: /Organisation/
public ActionResult Update()
{
var fisherman = new RoleType {Id = 1, Name = "Fisherman"};
var manager = new RoleType {Id = 2, Name = "Manager"};
var deckhand = new RoleType {Id = 3, Name = "Deckhand"};
var roleTypes = new List<RoleType>
{
fisherman, manager, deckhand
};
ViewBag.Roles = new SelectList(roleTypes, "Id", "Name");
return View(
new Organisation
{
Name = "Fish Co.",
People = new List<Person>
{
new Person
{
Name = "Squid",
RoleType = fisherman
},
new Person
{
Name = "Michael",
RoleType = manager
},
new Person
{
Name = "John",
RoleType = deckhand
}
}
});
}
[HttpPost]
public ActionResult Update(Organisation org)
{
return View();
}
}
public class Organisation
{
public string Name { get; set; }
public IList<Person> People { get; set; }
}
public class Person
{
public string Name { get; set; }
public RoleType RoleType { get; set; }
}
public class RoleType
{
public int Id { get; set; }
public string Name { get; set; }
}在Update.cshtml中
@model Models.Organisation
<form action="" method="post" enctype="multipart/form-data">
@Html.EditorFor(x => x.Name)
@Html.EditorFor(x => x.People)
<input type="submit"/>
</form>在EditorTemplates Person.cshtml中:
@model Models.Person
@Html.EditorFor(x => x.Name)
@if(Model != null)
{
@Html.DropDownListFor( x => x.RoleType.Id, (SelectList)ViewBag.Roles)
}我希望能够进入一个页面,在那里我可以更新组织名称、人员名称和他们的角色。问题是我不能为dropdowns设置选定的项目。我以为x => x.RoleType.Id会帮我做这件事。
有人知道我怎么才能让它工作吗?
发布于 2013-04-27 16:34:38
试试这个构造函数:SelectList Constructor (IEnumerable, String, String, Object)
public SelectList(
IEnumerable items,
string dataValueField,
string dataTextField,
Object selectedValue
)如下所示:
@Html.DropDownListFor( x => x.RoleType.Id, new SelectList((List<RoleType>)ViewBag.Roles, "Id", "Name", Model.RoleType.Id))https://stackoverflow.com/questions/16249853
复制相似问题