0

我有以下代码:

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; }
    }

在更新.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)
}

我期待能够进入一个可以更新组织名称、人员名称及其角色的页面。问题是我无法为下拉菜单设置所选项目。我以为x => x.RoleType.Id会为我做这件事。

有谁知道我怎样才能让它工作?

4

1 回答 1

1

试试这个构造函数: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))
于 2013-04-27T08:34:38.160 回答