2012-03-09 68 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