问题描述
我是新手与ASP.Net MVC 5,我有一个问题理解的DropDownList。
I'm newbie with ASP.Net MVC 5 and I'm having a problem understanding the dropdownlist.
我想表明,绑定一个DTO对象(因为形式不映射一对一数据库表)的形式。我的表必须显示以下字段:
I want show a form that binds a DTO object (because that form doesn't map one to one a database table). My form must show the following fields:
Name (edit box)
Address (edit box)
Type (dropdownlist that show always 3 fixed values: "Type1", "Type2" and "Type3"
我怎么能写我的DTO对象类和两个创建行动(的一个表现形式,另一种处理后)?
How can I write my DTO object class and the two Create actions (the one that show the form and the other that handle the post)?
我找到了一些解决方案使用了枚举
的DTO的对象,其他人使用该 viewbag
在创建行动(GET)...我很困惑!
I found some solutions that use the enum
in the DTO objects, others that use the viewbag
in the create action (GET)...I'm confused!!!
推荐答案
技巧是使用SelectListItem和使用DropDownFor。
Trick is to use SelectListItem and use DropDownFor.
创建您的视图模型中的财产像
Create a property on your view model like
public class ViewModel {
string SelectedItem { get; set; }
List<SelectListItem> Items { get; set; }
}
在你的控制器:
public ActionResult Edit() {
var items = new List<SelectListItem>() {
new SelectListItem() {Text = "Option1Text", Value = "Value1Text"},
new SelectListItem() {Text = "Option1Text", Value = "Value1Text"},
new SelectListItem() {Text = "Option1Text", Value = "Value1Text"}};
var model = new ViewModel() { Items = items };
return View(model);
};
在你看来
@model ViewModel
@Html.DropDownFor(x => x.SelectedItem, Model.Items)
您可以再拿到所选择的价值你的行动:
You can then get the selected value in your action:
[HttpPost]
public ActionResult Edit(ViewModel model) {
var whatWasSelected = model.SelectedItem; // This will be "OptionXValue"
// Do more things
}
您应该也重新填充的任何行动响应表单提交,如果你要重新渲染视图的选择列表项。这是因为选择的集合不传送在原始请求,因此,ASP.NET MVC不知道如何通过本身重建集合。通过这样做,你会想设置所选项目SelectListItem集合中时,为避免任何讨厌的例外。总体响应行动看起来更像是:
You should also re-populate the select list items on whatever action responds to the form submission if you're going to re-render the view. This is because the collection of options are not transmitted over the original request and therefore ASP.NET MVC doesn't know how to rebuild the collection by itself. By doing this you'll avoid any nasty exceptions when trying to set the selected item in the collection of SelectListItem. Overall the responding action would look more like:
[HttpPost]
public ActionResult Edit(ViewModel model) {
var items = new List<SelectListItem>() {
new SelectListItem() {Text = "Option1Text", Value = "Value1Text"},
new SelectListItem() {Text = "Option1Text", Value = "Value1Text"},
new SelectListItem() {Text = "Option1Text", Value = "Value1Text"}};
model.Items = items;
var whatWasSelected = model.SelectedItem; // This will be "OptionXValue"
// Do more things
}
这篇关于ASP MVC如何绑定的dropdownlist的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!