如何填充从下拉列表形式的价值? [英] How to populate a form value from a drop-down?
问题描述
后续从这个问题:如果我想从下拉计算根据用户的选择值下降列表,这个值放到一个表单变量/模型属性,我该怎么做呢?
Follow-on from this question: If I want to calculate a value based on a user's selection from a drop down list, and put that value into a form variable/model property, how do I do that?
推荐答案
说真的,如果我有一个建议给任何ASP.NET MVC开发,这将是:使用视图模型,而忘记了ViewBag /的ViewData 的。在是这样的解决方案,以他的问题/问题99%的情况。
Really, if I had a single advice to give any ASP.NET MVC developer that would be: use a view model and forget about ViewBag/ViewData. In 99% of the cases that is the solution to his questions/problems.
因此,这里的最小视图模式,将让你正确地重新present一个下拉列表:
So here's the minimal view model that will allow you to properly represent a dropdown list:
public class MyViewModel
{
// a scalar property on the view model to hold the selected value
[DisplayName("item")]
[Required]
public string ItemId { get; set; }
// a collection to represent the list of available options
// in the drop down
public IEnumerable<SelectListItem> Items { get; set; }
... and some other properties that your view might require
}
再有一个控制器操作将填充并通过这个视图模型到视图:
then have a controller action that will populate and pass this view model to the view:
public ActionResult Index()
{
var model = new MyViewModel
{
// TODO: those values probably come from your database or something
Items = new[]
{
new SelectListItem { Value = "1", Text = "item 1" },
new SelectListItem { Value = "2", Text = "item 2" },
new SelectListItem { Value = "3", Text = "item 3" },
}
};
return View(model);
}
,那么你可以有一个相应的强类型的视图可能包含一个表单,并在下拉列表这个视图模型:
then you could have a corresponding strongly typed view to this view model that could contain a form and the dropdown list:
@model MyViewModel
@using (Html.BeginForm())
{
@Html.LabelFor(x => x.ItemId)
@Html.DropDownListFor(x => x.ItemId, Model.Items, "--Select One--")
<button type="submit">OK</button>
}
最后你可以有你的控制器此表格将被提交,并在其内部,您将能够检索从下拉列表中选定的值上的相应动作:
and finally you could have a corresponding action on your controller to which this form will be submitted and inside which you will be able to retrieve the selected value from the dropdown list:
[HttpPost]
public ActionResult Index(MyViewModel model)
{
// model.ItemId will contain the selected value from the dropdown list
...
}
这篇关于如何填充从下拉列表形式的价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!