如何使用MVC创建一个包含静态元素(硬编码)的简单下拉列表?
看起来像这样:
<select name="type_ins">
<option value="1">First</option>
<option value="2">Second</option>
</select>
答案 0 :(得分:2)
检查以下代码
Html.DropDownList(
string name,
IEnumerable<SelectListItem> selectList,
string optionLabel,
object htmlAttributes)
List<SelectListItem> items = new List<SelectListItem>();
items.Add(new SelectListItem
{
Text = "Swimming",
Value = "1"
});
items.Add(new SelectListItem
{
Text = "Cycling",
Value = "2",
Selected = true
});
items.Add(new SelectListItem
{
Text = "Running",
Value = "3"
});
同时检查此link
答案 1 :(得分:0)
在模型中
public class DemoModel
{
public string SelectedValue { get; set; }
public IEnumerable<SelectListItem> Values
{
get
{
return new[]
{
new SelectListItem { Value = "1", Text = "Test 1" },
new SelectListItem { Value = "2", Text = "Test 2" },
};
}
}
}
在控制器
中public ActionResult Index()
{
var model = new DemoModel();
return View(model);
}
在视图中
@model DemoModel
@Html.DropDownListFor(x => x.SelectedValue, Model.Values)