MVC3 DropDownListFor - 一个简单的例子吗? [英] MVC3 DropDownListFor - a simple example?
问题描述
我有我的MVC3应用与 DropDownListFor
麻烦。我可以使用计算器来找出如何让他们出现在视图中,但现在我不知道该怎么当它提交捕捉值在其相应属性的视图模型。为了得到这个工作,我不得不创建一个内部类,它有一个ID和值属性,那么我不得不使用的IEnumerable<的Contrib>
来满足 DropDownListFor
参数要求。然而,现在怎么MVC FW应该映射是在该下拉列表中选择回到简单的字符串属性在我的视图模型的价值?
I'm having trouble with DropDownListFor
in my MVC3 app. I was able to use StackOverflow to figure out how to get them to appear on the View, but now I don't know how to capture the values in its corresponding properties on the View Model when it's submitted. In order to get this to work I had to create an inner class that had an ID and a value property, then I had to use an IEnumerable<Contrib>
to satisfy the DropDownListFor
parameter requirements. Now, however, how is MVC FW supposed to map the value that is selected on this drop-down back into the simple string property on my view model?
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; }
}
在我看来,我把下拉页面上是这样的:
In my View I place the dropdown on the page like this:
<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
是(当然)无效。
When I submit the form the ContribType
is (of course) null.
什么是做正确的方法是什么?
What is the correct way to do this?
推荐答案
您应该这样做:
@Html.DropDownListFor(m => m.ContribType,
new SelectList(Model.ContribTypeOptions,
"ContribId", "Value",
Model.ContribTypeOptions.First().ContribId))
其中:
m => m.ContribType
是结果值将是一个属性。
结果
和SELECT列表构造函数的最后一个参数是一个选择的值
is a property where the result value will be.
And the last param of Select list constructor is a selected value
这篇关于MVC3 DropDownListFor - 一个简单的例子吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!