我在DropDownList中显示数据:( im usign datacontext)
控制器:
var query = newdb.Incident.Select(c => new {c.ID,c.Name}); ViewBag.items = new SelectList(query.AsEnumerable(),“ID”,“Name”);
查看:
@ Html.DropDownList(“items”,(SelectList)ViewBag.items,“ - 选择一个事件 - ”)
问题:
我想知道如何从DropDownlist中选择一个项目并将参数发送回所选项目的控制器,因为我试试这个并且不起作用:
@using(Html.BeginForm(“er”,“er”,FormMethod.Post,new {id = 4})){
@ Html.DropDownList(“items”,(SelectList)ViewBag.items,“ - 选择一个事件 - ”)}
我希望有人可以帮助玩笑
答案 0 :(得分:1)
您可以将所选值作为SelectList构造函数的第4个参数传递:
var query = newdb.Incident.Select(c => new { c.ID, c.Name });
ViewBag.items = new SelectList(query.AsEnumerable(), "ID", "Name", "4");
并且在您的视图中确保您使用不同的值作为DropDownList帮助器的第一个参数,因为您现在使用的是"items"
,这是错误的,因为第一个参数表示生成的下拉列表的名称将在控制器中用于获取所选值:
@Html.DropDownList(
"selectedIncidentId",
(SelectList) ViewBag.items,
"--Select a Incident--"
)
我还建议您使用视图模型和DropDownListFor帮助器的强类型版本:
public class IncidentsViewModel
{
public int? SelectedIncidentId { get; set; }
public IEnumerable<SelectListItem> Incidents { get; set; }
}
然后:
public ActionResult Foo()
{
var incidents = newdb.Incident.ToList().Select(c => new SelectListItem
{
Value = c.ID.ToString(),
Text = c.Name
});
var model = new IncidentsViewModel
{
SelectedIncidentId = 4, // preselect an incident with id = 4
Incidents = incidents
}
return View(model);
}
并在您的强类型视图中:
@model IncidentsViewModel
@using (Html.BeginForm())
{
@Html.DropDownListFor(
x => x.SelectedIncidentId,
Model.Incidents,
"--Select a Incident--"
)
<button type="submit">OK</button>
}