如果你为你的视图创建 ViewModel 会更好:
public class SampleViewModel
{
public string DropDownListValue { get; set; }
}
然后在控制器的 get 方法中:
public ActionResult SomeAction()
{
var org = GetOrg(); //your org
var orgNames = GetOrgNames(); //your orgNames
// . . .
ViewBag.DropDownListValue = new SelectList(org.Select(s =>
new SampleViewModel
{
DropDownListValue = $"{s} - {orgNames[s]}"
}, "DropDownListValue", "DropDownListValue");
return View(new SampleViewModel())
}
您的SomeAction 查看:
@model YourAppNamespace.SampleViewModel
<h1>Hello Stranger</h1>
@using (Html.BeginForm())
{
@Html.DropDownList("DropDownListValue")
<input type="submit" value="Submit"/>
}
请注意:
DropDownList 帮助器用于创建 HTML 选择列表
需要IEnumerable<SelectListItem>,无论是明确的还是
含蓄地。也就是说,你可以通过IEnumerable<SelectListItem>
明确地添加到 DropDownList 助手,或者您可以添加
IEnumerable<SelectListItem> 到 ViewBag 使用相同的名称
SelectListItem 作为模型属性。
我们在这里使用了隐式传递,即我们为SelectListItem 和ViewBag 使用了相同的名称(即DropDownListValue)。
那么当你点击Submit时,你需要HttpPost方法为SomeAction:
[HttpPost]
public ActionResult SomeAction(SampleViewModel model)
{
var org = GetOrg(); //your org
var orgNames = GetOrgNames(); //your orgNames
//. . . Validation etc..
ViewBag.DropDownListValue = new SelectList(org.Select(s =>
new SampleViewModel
{
DropDownListValue = $"{s} - {orgNames[s]}"
}, "DropDownListValue", "DropDownListValue", model.DropDownListValue);
var doSomething = model.DropDownListValue; //Your selected value from DropDownList
return View(model)
}
参考:DotNetFiddle Example、
Using the DropDownList Helper with ASP.NET MVC