Tre*_*oll 110 c# html.dropdownlistfor asp.net-mvc-3
我DropDownListFor在我的MVC3应用程序中遇到了麻烦.我能够使用StackOverflow来弄清楚如何让它们出现在View上,但现在我不知道在提交时如何捕获视图模型中相应属性中的值.为了使其工作,我必须创建一个具有ID和value属性的内部类,然后我必须使用a 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; }
}
Run Code Online (Sandbox Code Playgroud)
在我的视图中,我将下拉列表放在页面上,如下所示:
<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>
Run Code Online (Sandbox Code Playgroud)
当我提交表格时ContribType(当然)为空.
这样做的正确方法是什么?
Ser*_*ruk 165
你应该这样做:
@Html.DropDownListFor(m => m.ContribType,
new SelectList(Model.ContribTypeOptions,
"ContribId", "Value"))
Run Code Online (Sandbox Code Playgroud)
哪里:
m => m.ContribType
Run Code Online (Sandbox Code Playgroud)
是结果值的属性.
我认为这会有所帮助:在Controller中获取列表项和选定的值
public ActionResult Edit(int id)
{
ItemsStore item = itemStoreRepository.FindById(id);
ViewBag.CategoryId = new SelectList(categoryRepository.Query().Get(),
"Id", "Name",item.CategoryId);
// ViewBag to pass values to View and SelectList
//(get list of items,valuefield,textfield,selectedValue)
return View(item);
}
Run Code Online (Sandbox Code Playgroud)
并在视图中
@Html.DropDownList("CategoryId",String.Empty)
Run Code Online (Sandbox Code Playgroud)
要在DropDownList中绑定动态数据,您可以执行以下操作:
在Controller中创建ViewBag,如下所示
ViewBag.ContribTypeOptions = yourFunctionValue();
Run Code Online (Sandbox Code Playgroud)
现在在视图中使用此值如下所示:
@Html.DropDownListFor(m => m.ContribType,
new SelectList(@ViewBag.ContribTypeOptions, "ContribId",
"Value", Model.ContribTypeOptions.First().ContribId),
"Select, please")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
222015 次 |
| 最近记录: |