【发布时间】:2011-08-22 03:47:55
【问题描述】:
我在我的 MVC3 应用程序中遇到了 DropDownListFor 问题。我能够使用 StackOverflow 来弄清楚如何让它们出现在视图上,但现在我不知道如何在提交视图模型时捕获其相应属性中的值。为了让它工作,我必须创建一个具有 ID 和 value 属性的内部类,然后我必须使用 IEnumerable<Contrib> 来满足 DropDownListFor 参数要求。但是,现在,MVC FW 应该如何将在此下拉列表中选择的值映射回我的视图模型上的简单字符串属性?
public class MyViewModelClass
{
public class Contrib
{
public int ContribId { get; set; }
public string Value { get; set; }
}
public IEnumerable<Contrib> ContribTypeOptions =
new List<Contrib>
{
new Contrib {ContribId = 0, Value = "Payroll Deduction"},
new Contrib {ContribId = 1, Value = "Bill Me"}
};
[DisplayName("Contribution Type")]
public string ContribType { get; set; }
}
在我的视图中,我将下拉列表放在页面上,如下所示:
<div class="editor-label">
@Html.LabelFor(m => m.ContribType)
</div>
<div class="editor-field">
@Html.DropDownListFor(m => m.ContribTypeOptions.First().ContribId,
new SelectList(Model.ContribTypeOptions, "ContribId", "Value"))
</div>
当我提交表单时,ContribType(当然)为空。
这样做的正确方法是什么?
【问题讨论】:
标签: c# asp.net-mvc-3 html.dropdownlistfor