ASP.NET MVC中的SelectLists将值分配给模型属性

时间:2014-05-29 01:53:36

标签: asp.net-mvc

我的问题与ASP.NET MVC 4有关。

我在操作方法中使用了此代码:

public ActionResult Create()
{
     var allProfiles = db.Profiles.ToList();
     var profsSelectList = new SelectList(allProfiles, "Id", "ProfileName");
     ViewBag.allProfiles = profsSelectList;
     return View();
}

我的观点有这个:

<div class="editor-field">
    @Html.DropDownList("allProfiles")
    @Html.ValidationMessageFor(model => model.Author)
</div>

我的目标是提供一个包含allProfiles.ProfileName的DropDownList 每个选择项的文本。 当他们选择其中一个时,&#34; Id&#34;属性已分配给Model.Author。 提交表单时,我希望POST方法显示&#34; Message&#34;谁的 作者包含该整数。

我的DropDownList正确显示了ProfileNames列表。但表格提交 始终将Model.Author设置为0。

我做错了什么?

1 个答案:

答案 0 :(得分:-1)

我解决了自己的问题。

为了使您的视图包中存在的选择列表成为一个有价值的下拉列表 设置模型的属性(在视图中),以下是解决方案:

GET创建操作方法

public ActionResult Create()
{
    var allProfiles = db.Profiles.ToList();
    var profsSelectList = new SelectList(allProfiles, "Id", "ProfileName");
    ViewBag.allProfiles = profsSelectList;
    return View();
}

创建下拉列表的视图

<div class="editor-field">
     @Html.DropDownListFor(m=>m.Author, (IEnumerable<SelectListItem>)ViewBag.allProfiles)
</div>

你有它。