【问题标题】:DropDownList asp.net mvc 3 problemsDropDownList asp.net mvc 3 问题
【发布时间】:2012-03-26 12:23:52
【问题描述】:

i 在 DropDownList 中显示一个数据:(im ussign 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, "--Select a Incident--")

问题:

我想知道如何从 DropDownlist 中选择一个项目并将参数发送回所选项目的控制器,因为我尝试了这个并且不起作用:

@using (Html.BeginForm("er", "er", FormMethod.Post, new { id = 4 })){

@Html.DropDownList("items", (SelectList) ViewBag.items, "--Select a Incident--")}

希望有人能帮忙笑

【问题讨论】:

标签: asp.net-mvc


【解决方案1】:

您可以将所选值作为 SelectList 构造函数的第四个参数传递:

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>
}

【讨论】:

猜你喜欢
  • 2012-03-11
  • 1970-01-01
  • 1970-01-01
  • 2011-07-12
  • 2011-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多