2011-11-11 16 views
0

MVC3でドロップダウンリストの選択した値を維持するにはどうすればよいですか?MVC3のドロップダウンリストの状態を維持する

Iドロップダウンリストを作成するには、次のコードを使用しています:

<%= Html.DropDownList("PEDropDown", 
     (IEnumerable<SelectListItem>)ViewData["PEDropDown"], 
     new { onchange = "this.form.action='/Screener/Screener';this.form.submit();" } 
)%> 

答えて

0

私は私はあなたが何をしたいかを取得、100%わからないんだけど、私はあなたが選択した値を取得したいと仮定ドロップダウンリストからその場合

new { onchange = "alert(this.options[this.selectedIndex].value);" } 

私はあなたがここで値

+0

問題は、値がドロップダウンから選択された後に、ポストメソッドが呼び出されて、選択された値が失われていることです。 – user1019480

1

で何をしたいのか分からないので、私は、今のアラートに入れるには、私が使用し、一つの例です。私はわからない、これは別の方法あなたが

<%=Html.DropDownList("ddlCategories", IEnumerable<SelectListItem>)ViewData["PEDropDown"], "CategoryId", "CategoryName", Model.CategoryId), "Select Category", new { onchange = "this.form.action='/Screener/Screener';this.form.submit();"})%> 

のDropDownList

を埋めるために使用する方法です、

List<SelectListItem> CategoryList = new List<SelectListItem>(); 
       foreach (var item in Categories) 
       { 

        CategoryList.Add(new SelectListItem 
        { 
         Selected = Model.CategoryId, 
         Text = item.CategoryName, Value = Convert.ToString(item.CategoryId) }); 
       } 
ViewData["PEDropDown"]=CategoryList; 

を次のようにコントローラで選択リストを作成し、

<%:Html.DropDownList("ddlCategories",IEnumerable<SelectListItem>)ViewData["PEDropDown"], "CategoryId", "CategoryName", new { onchange = "this.form.action='/Screener/Screener';this.form.submit();"})%> 
としてビューで使用します
0

コントローラに値を渡してから、コントローラのSelectListItemのリストを入力します。

public actionresult yourmethod (int idToPass) 
{ 

List<SelectListItem> SLIList = new List<SelectListItem>(); 
foreach (Model model in dropdownList) 
{ 
    SelectListItem SLI = new SelectListItem(); 
    SLI.text = model.CategoryName; 
    SLI.selected = model.CategoryId == idToPass; 
    SLIList.Add(SLI); 
} 
    ViewData["myDDL"] = SLIList; 
} 
0

これを試すことができます。 ViewBagの代わりのViewDataを使用して (私が提案する、モデルオブジェクトを使用することをお勧めします)

Html.DropDownList("PEDropDown", new SelectList(ViewBag.PEDropDown, "Key", "Value", Model.PEDropDownSelectedValue), new { onchange = "document.location.href = '/ControllerName/ActionMethod?selectedValue=' + this.options[this.selectedIndex].value;" })) 

SelectListので四番目の引数は、選択した値です。モデルオブジェクトを使用して渡す必要があります。 特定のアクションメソッドを呼び出すときは、以下のようにモデルオブジェクトを設定します。

public ActionResult ActionMethod(string selectedValue) 
{ 
    ViewModelPE objModel = new ViewModelPE(); 
    // populate the dropdown, since you lost the list in Viewbag 
    ViewBag.PEDropDown = functionReturningListPEDropDown(); 
    objModel.PEDropDownSelectedValue = selectedValue; 
    return View(objModel); 
    // You may use the model object to pass the list too instead of ViewBag (ViewData in your case) 
} 
関連する問題