我在使用这个下拉框时遇到问题,似乎无法正确设置,这是代码:
View (索引.cshtml):
@using EvaSimulator.Models
@Model EvaSimulator.Models.ModelVariables
@{
ViewBag.Title = "Index";
ModelVariables mv = new ModelVariables();
}
@using (Html.BeginForm("DropDownBox", "Home", FormMethod.Get))
{
@Html.DropDownList("dropdownbox", )
<button type="submit"></button>
}
<p>@Model.dropDownList</p>
模型(ModelVariables.cs):
public string dropDownList = "";
Controller (HomeController.cs):
public ActionResult DropDownBox(string dropdownbox)
{
ModelVariables mv = new ModelVariables();
mv.dropDownList = dropdownbox;
return this.View("Index", mv);
}
这看起来确实不错,我只是在寻找一个简单的解决方案,创建一个下拉式多选列表框,无论我提交什么,我都会得到值列表并将它们打印在 <p>
中 View 中的标记 ( @Model.dropDownList
)
最佳答案
首先,您应该为 IEnumerable<SelectListItem>
类型的下拉数据向 View 模型类添加一个新属性。 .我们将添加第二个数组类型的属性(因为您需要多选)来保存选定的选项值。
public class ModelVariables
{
public IEnumerable<SelectListItem> Options {set;get;}
public string[] SelectedOptions { set;get;}
}
现在在您的 GET 操作中,创建此 View 模型的对象,填充 Options
属性并发送到 View 。
public ActionResult Create()
{
var vm = new ModelVariables();
vm.Options = new List<SelectListItem> {
new SelectListItem { Value="MI", Text="Michigan" },
new SelectListItem { Value="NY", Text="New York" },
};
return View(vm);
}
现在在您的 View 中,使用 Html.ListBoxFor
辅助方法
@model ModelVariables
@using(Html.BeginForm())
{
<label> Select items <label>
@Html.ListBoxFor(s=>s.SelectedOptions,Model.Options)
<input type="submit" />
}
现在在您的 HttpPost 操作中,您可以拥有与您的方法参数相同的 View 模型,并且模型绑定(bind)器将能够将发布的表单数据映射到该对象的对象。从 UI 中选择的选项将在 SelectedOptions
中可用。 View 模型对象的属性。
[HttpPost]
public ActionResult Create(ModelVariables model)
{
// check model.SelectedOptions property value
// to do : Return something
}
https://stackoverflow.com/questions/37304543/