2013-08-06 19 views
0

在我的應用程序中,我有兩個下拉列表。首先顯示國家值,其次顯示所選國家的狀態。這些值將生成並顯示在兩個下拉列表中。但在發佈後,兩個dropdownlist都會返回模型值的id,而不是名稱或值。如何在後期綁定dropdownlist的選定項目文本? 型號:如何將模型值綁定到下拉列表中的選定項目文本mvc4

public string State { get; set; } 
public string Country { get; set; } 
public SelectList CountryList { get; set; } 
public SelectList RegionList { get; set; } 
public class Countries 
{ 
    public string ID { get; set; } 
    public string Name { get; set; } 
} 
public class Region 
{ 
    public string ID { get; set; } 
    public string Name { get; set; } 
} 

查看

@Html.DropDownListFor(model =>model.State, new SelectList(Model.RegionList, "Value", "Text", Model.RegionList.SelectedValue))  
@Html.DropDownListFor(model => model.Country, new SelectList(Model.CountryList, "Value", "Text", Model.CountryList.SelectedValue), new { data_url = Url.Action("GetRegionDetail", "WPindex") }) 


<script type="text/javascript"> 
      $(document).ready(function() { 
       $("#Country").change(function() {     
        $("#State").empty();  
      var url =$(this).data(url); 
      var Id = $('#Country option:selected').attr('value'); 
        $.getJSON(url, { ID: Id }, 
         function (data) { 
          jQuery.each(data, function (key, Region) { 
           $("#State").append($("<option></option>").val(Region.ID).html(Region.Name)); 
          } 
          ); 
         }); 
       }); 
     }); 
</script> 

控制器:

public JsonResult GetRegionDetail(int ID) 
    { 
     AddressModel amodel = new AddressModel(); 
     List<Model.Region> objRegion = new List<Model.Region>(); 
     objRegion = GetRegionList(ID); 
     SelectList objlistofRegiontobind = new SelectList(objRegion, "ID", "Name", 0); 
     amodel.RegionList = objlistofRegiontobind; 
     return Json(objRegion, JsonRequestBehavior.AllowGet); 
    } 
[HttpPost] 
public ActionResult UpdateDetails(Model objmodel) 
{ 
    string state = objmodel.State; // returns ID and not Name (selected text) 
    string country = objmodel.Country; // returns ID and not Name 
} 

回答

1

當你定義在HTML中的下拉列表中,每個optionvaluetexttext值的屬性顯示給用戶和value是該下拉列表的「選定值」。將表單發佈到控制器時,只發布value。如果您希望使用名稱而不是要發佈的ID,只需將下拉列表項的value屬性設置爲源數據的name即可。

例如,當你填入你的狀態下拉菜單,你可以做這樣的:

$("#State").append($("<option></option>").val(Region.Name).html(Region.Name)); 
1

這不是一個問題。你希望DropDownList給你選定的值,在這種情況下是ID,而不是文本。所以,我建議你改變你的視圖模型的屬性有以下:

public int StateID { get; set; } 
public int CountryID { get; set; } 
public SelectList CountryList { get; set; } 
public SelectList RegionList { get; set; } 

但是,如果你不想要的ID,你可以這樣定義你的DropDownLists:

@Html.DropDownListFor(model => model.State, new SelectList(Model.RegionList, Model.State))  
@Html.DropDownListFor(model => model.Country, new SelectList(Model.CountryList, Model.Country), new { data_url = Url.Action("GetRegionDetail", "WPindex") }) 
相關問題