MVC3 DropDownListFor - 一个简单的例子? [英] MVC3 DropDownListFor - a simple example?
问题描述
我的 MVC3 应用程序中的 DropDownListFor
有问题.我能够使用 StackOverflow 来弄清楚如何让它们出现在视图上,但现在我不知道如何在提交时捕获视图模型上其相应属性中的值.为了让它起作用,我必须创建一个具有 ID 和 value 属性的内部类,然后我不得不使用 IEnumerable
来满足 DropDownListFor
> 参数要求.但是,现在 MVC FW 应该如何将在此下拉列表中选择的值映射回我的视图模型上的简单字符串属性?
公共类 MyViewModelClass{公开课贡献{公共 int ContribId { 获取;放;}公共字符串值 { 获取;放;}}公共 IEnumerableContribTypeOptions =新列表<贡献>{new Contrib {ContribId = 0, Value = "Payroll Deduction"},new Contrib {ContribId = 1, Value = "Bill Me"}};[DisplayName("投稿类型")]公共字符串 ContribType { 获取;放;}}
在我的视图中,我将下拉菜单放置在页面上,如下所示:
@Html.LabelFor(m => m.ContribType)<div class="editor-field">@Html.DropDownListFor(m => m.ContribTypeOptions.First().ContribId,new SelectList(Model.ContribTypeOptions, "ContribId", "Value"))
当我提交表单时,ContribType
(当然)为空.
这样做的正确方法是什么?
你应该这样做:
@Html.DropDownListFor(m => m.ContribType,新的 SelectList(Model.ContribTypeOptions,"ContribId", "价值"))
地点:
m =>m.ContribType
是结果值所在的属性.
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>
When I submit the form the ContribType
is (of course) null.
What is the correct way to do this?
You should do like this:
@Html.DropDownListFor(m => m.ContribType,
new SelectList(Model.ContribTypeOptions,
"ContribId", "Value"))
Where:
m => m.ContribType
is a property where the result value will be.
这篇关于MVC3 DropDownListFor - 一个简单的例子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!