2015-12-31 33 views
0

獲得所選項目使用JavaScript用於填充一個名爲「組」列表中。從DropDownList的

然後,我創建一個DropDownList:

<div class="form-group"> 
    <div class="col-md-10"> 
     @Html.DropDownList("groups", new SelectList(string.Empty, "Value", "Text"), "Choose...") 
    </div> 
</div> 

DropDownList控件顯示細膩。

我需要做的是從「羣體」的model.group_id分配選擇的值。 我不知道如何獲取在控制器方法中的DropDownList中選擇的項目。感謝您的任何建議。

+0

這不是C#;這是Javascript和Razor和Bootstrap。 –

+0

控制器是在C#中,我問了有關控制器。 – stkvhw

+0

你是谷歌嗎?你可以使用DropDownListFor? –

回答

0

假設您在名爲group_id這樣的表單中有一個窗體域,您要設置從下拉列表那場因某種原因選擇的值,

@Html.HiddenFor(s=>s.group_id) 
<div class="form-group">  
    @Html.DropDownList("groups",new SelectList(string.Empty, "Value", "Text"), "Choose...") 
</div> 

你可以聽的變化下拉的事件,並獲得選擇的選項值並設置爲GROUP_ID

$(function(){ 

    $("#groups").change(function(e){ 
     var v=$(this).val(); 
     $("#group_id").val(v); 
    });  

}); 

我不知道你爲什麼加載通過JavaScript的下拉菜單的內容,但也有其他更好的方法來呈現一個下拉列表,選擇通過價值回到你的身上如this post中所解釋的。

一個SelectedGroup屬性添加到您的視圖模型

public class CreateSomethingViewModel 
{ 
    public int SelectedGroup {set;get;} 
    public List<SelectListItem> Groups {set;get;} 
} 

,並在你的GET操作,如果要加載組,你可以做到這一點

public ActionResult Create() 
{ 
    var vm = new CreateSomethingViewModel(); 
    //Hard coded for demo. You may replace with your db entries (see below) 
    vm.Groups = new List<SelectListItem> { 
    new SelectListItem { Value="1","Chase bank" }, 
    new SelectListItem { Value="2","PNCbank" }, 
    new SelectListItem { Value="3","BOA" } 
    }; 
    return View(vm); 
} 

而且在你看來

@model CreateSomethingViewModel 
@using(Html.BeginForm()) 
{ 
    @Html.DropDownListFor(s=>s.SelectedGroup,Model.Groups) 
    <input type="submi" /> 
} 

有了這個,你不需要使用任何js代碼(即使你加載下拉續ent通過JavaScript),當用戶更改下拉選項值時,它將被設置爲SelectedGroup屬性的值。

[HttpPost] 
public ActionResult Create(CreateSomethingViewModel model) 
{ 
    // check model.SelectedGroup 
    // to do : Save and return/redirect 
} 
+0

我這樣做,因爲我有一個父下拉列表,並根據父列表中選擇的值,sednd下拉列表填充在JavaScript中。那好嗎? – stkvhw

+0

我是這麼想的。沒事兒。如果Chris Pratt在他的回答中提到的,那麼您可以使用屬性名稱作爲第一個參數,如果這是您視圖模型的一部分。 – Shyju

+1

謝謝你,你的回答非常有幫助,現在一切正常。 – stkvhw

1

如果你需要它綁定到group_id然後使用該作爲名稱:

@Html.DropDownList("group_id", ...) 

,或者甚至更好,使用強類型的幫手:

@Html.DropDownListFor(m => m.group_id, ...)