如何让卓尔选择下拉列表值在行动? [英] how to get selected drow down list value in Action?
本文介绍了如何让卓尔选择下拉列表值在行动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在MVC的Web应用程序是与模型,其中向下正在生成一滴强类型的模型/绑定的视图。
In MVC web app it is a view with strongly typed model where a drop down is being generated / bind by model.
下面是视图code:
@model LoanViewModel
<form class="wrapper minheight homeloan-form border-top" id="homeloan-form" method="post" action="LeadContact" novalidate="novalidate">
<p>@Html.ValidationSummary()</p>
<p>Select an Item : @Html.DropDownListFor(x => x.HomeLoanLead.Items, new SelectList(Model.HomeLoanLead.Items), "--Choose any Item--")</p>
<div class="formnav row">
<button class="">Show Top Home Loans <i class="fa fa-chevron-right"></i></button>
</div>
</form>
在模型中我为硬编码的下拉列表中选择:
In model I m hardcoding options for drop down list:
public List<string> Items
{
get { _items = new List<string>();
_items.Add("One");
_items.Add("Two");
_items.Add("Three");
return _items;
}
}
在回传我不能得到什么选择价值下拉。请指导我怎么去后的行动被选为该下拉值。
On post back I cant get what was selected value in drop down. Please guide me how to get in post action which drop down value was selected.
推荐答案
用一个简单的例子 Html.DropDownFor()
以显示选项列表并绑定到一个属性:
A simple example of using Html.DropDownFor()
to display a list of options and bind to a property:
型号
public class LoanViewModel
{
[Required]
[Display(Name="Select Item")]
public string Item { get; set; }
public SelectList ItemList { get; set; }
}
控制器
public ActionResult Edit()
{
LoanViewModel model = new LoanViewModel();
model.Item = "Two"; // this will now pre-select the second option in the view
ConfigureEditModel(model);
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(LoanViewModel model)
{
if (!ModelState.IsValid)
{
ConfigureEditModel(model); // repopulate select list
return View(model); // return the view to correct errors
}
// If you want to validate the the value is indeed one of the items
ConfigureEditModel(model);
if (!model.ItemList.Contains(model.Item))
{
ModelState.AddModelError(string.Empty, "I'm secure!");
return View(model);
}
string selectedItem = model.Item;
....
// save and redirect
}
private void ConfigureEditModel(LoanViewModel model)
{
List<string> items = new List<string>() { "One", "Two", "Three" };
model.ItemList = new SelectList(items); // create the options
// any other common stuff
}
查看
@model LoanViewModel
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
@Html.DisplayFor(m => m.Item)
@Html.DropDownListFor(m => m.Item, Model.ItemList), "--Choose any Item--")
@Html.ValidationMessageFor(m => m.Item)
<input type="submit" value="Submit" />
}
这篇关于如何让卓尔选择下拉列表值在行动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文