2012-03-09 133 views
0

我在DropDownList显示数据:(IM usign的datacontext)DropDownList的asp.net MVC 3个问题

控制器:

变种查询= newdb.Incident.Select(C =>新的{c.ID ,c.Name}); ViewBag.items = new SelectList(query.AsEnumerable(),“ID”,“Name”);

查看:

@ Html.DropDownList( “项目”,(的SelectList)ViewBag.items “ - 选择一个Incident--”)

问题:

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

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

@ Html.DropDownList( “项目”,(的SelectList)ViewBag.items “ - 选择一个Incident--”)}

我希望有人能helpLaughing

+0

请参阅我的教程[使用DropDownList框和jQuery] [1]和[我的博客Cascading DropDownList在ASP.Net MVC] [2] [1]:http://www.asp.net/mvc/tutorials/javascript/working-with-the-dropdownlist-box-and-jquery/using-the-dropdownlist-helper-with-aspnet-mvc [2]:http://blogs.msdn.com/b/rickandy/archive /2012/01/09/cascasding-dropdownlist-in-asp-net-mvc.aspx – RickAndMSFT 2012-03-09 20:24:14

回答

1

您可以通过所选择的值作为第四选择列表的构造函数的参数:

var query = newdb.Incident.Select(c => new { c.ID, c.Name }); 
ViewBag.items = new SelectList(query.AsEnumerable(), "ID", "Name", "4"); 

,并在您的视图确保您使用的是不同的值作为第一个参数DropDownList的帮手,因为现在你正在使用"items"这是不对的,因为第一个参数代表将使用的生成的下拉列表的名称b ACK在控制器中获取所选值:

@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> 
} 
+0

或者你可以按照我的教程/博客看我的教程[使用DropDownList框和jQuery] [1]和[我的博客Cascading DropDownList在ASP.Net MVC] [2] [1]:http://www.asp.net/mvc/tutorials/javascript/working-with-the-dropdownlist-box-and-jquery/using-the-dropdownlist- helper-with-aspnet-mvc [2]:http://blogs.msdn.com/b/rickandy/archive/2012/01/09/cascasding-dropdownlist-in-asp-net-mvc.aspx – RickAndMSFT 2012-03-09 20:24:48