C# 未设置使用ViewBag SelectedItem的MVC SelectList
我有以下代码:C# 未设置使用ViewBag SelectedItem的MVC SelectList,c#,asp.net-mvc,C#,Asp.net Mvc,我有以下代码: public class OrganisationController : Controller { // // GET: /Organisation/ public ActionResult Update() { var fisherman = new RoleType {Id = 1, Name = "Fisherman"};
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; }
}
我希望能够进入一个页面,在那里我可以更新组织名称、人员名称和他们的角色。问题是我无法为下拉列表设置所选项目。我想x=>x.RoleType.Id
可以帮我完成这个任务
有人知道我如何让它工作吗?试试这个构造函数:
大概是这样的:
@Html.DropDownListFor( x => x.RoleType.Id, new SelectList((List<RoleType>)ViewBag.Roles, "Id", "Name", Model.RoleType.Id))
@Html.DropDownListFor(x=>x.RoleType.Id,新的SelectList((List)ViewBag.Roles,“Id”,“Name”,Model.RoleType.Id))
尝试过,但得到了,数据绑定:“System.Web.Mvc.SelectListItem”不包含名为“Id”的属性。@user2005657为ViewBag添加强制转换
奇怪,现在它无法将类型“System.Web.Mvc.SelectList”转换为“System.Collections.Generic.List”我不知道为什么它无法执行强制转换
@model Models.Person
@Html.EditorFor(x => x.Name)
@if(Model != null)
{
@Html.DropDownListFor( x => x.RoleType.Id, (SelectList)ViewBag.Roles)
}
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))