2012-03-09 19 views
0

iはDropDownListコントロールにデータを表示する:(IM usignのDataContext)のDropDownList asp.netのMVC 3つの問題

コントローラー:

VARクエリ= newdb.Incident.Select(C =>新しい{c.ID 、c.Name}); ViewBag.items = new SelectList(query.AsEnumerable()、 "ID"、 "Name");

ビュー:

@ Html.DropDownList( "Incident--を選びなさい - " "アイテム"、(SelectListの)ViewBag.items、)

問題:私は知りたい

どのように私はDropDownlistから項目を選択し、選択した項目のコントローラにパラメータを送り返すことができますか?これを試して、仕事をしないので、

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

Html.DropDownList @

( "アイテム"、(SelectListの)ViewBag.items、 "Incident--を--select")}

私は、誰かがhelpLaughing

+0

私のチュートリアル[DropDownList BoxとjQueryを使って作業する] [1] [ASP.Net MVCで私のブログCascading DropDownList] [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

答えて

1

あなたは第四として選択された値を渡すことができことを願ってSelectListのコンストラクタの引数:

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

とまたあなたのビューで、今あなたが間違っている"items"を使用しているため、最初の引数が表すので、あなたは、DropDownListのヘルパーの最初の引数として別の値を使用していることを確認してください生成されるドロップダウンリストの名前b

@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); 
} 
選択された値を取得するために、コントローラにackを

、強く型付きのビュー:

@model IncidentsViewModel 
@using (Html.BeginForm()) 
{ 
    @Html.DropDownListFor(
     x => x.SelectedIncidentId, 
     Model.Incidents, 
     "--Select a Incident--" 
    ) 

    <button type="submit">OK</button> 
} 
+0

または私のチュートリアル/ブログに従うことができます。チュートリアル[DropDownList BoxとjQueryを使って作業する] [1]と[My blog 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