2013-08-07 39 views
2

我試圖在我的應用程序的dropdownlist中實現編輯和更新。從模型中顯示下拉列表的值列表。但是選定的值不會顯示在下拉列表中。所選值也作爲下拉列表中的值列表填充。在Dropdownlist中編輯和更新mvc4

我的模型:

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

查看

@foreach (var item in Model.AddressList) 
{ 
    @Html.DropDownListFor(model => item.State, new SelectList(Model.Address.RegionList, "Value", "Text", Model.Address.RegionList.SelectedValue))              
} 

注:
item.State被填充,但不顯示值
model.address.regionlist填充並顯示

控制器

public ActionResult EditAddress(AddressTuple tmodel,int AddressID) 
{ 
    int country; 
    string customerID = 1; 
    List<AddressModel> amodel = new List<AddressModel>(); 
    amodel = GetAddressInfo(customerID, AddressID); // returns the selected value for dropdown 
    foreach (var item in amodel) 
    { 
     country = item.CountryId; 
    }    
    List<Region> objRegion = new List<Region>(); 
    objRegion = GetRegionList(id); // returns the list of values for dropdown 
    SelectList objlistofregiontobind = new SelectList(objRegion, "ID", "Name", 0); 
    atmodel.RegionList = objlistofregiontobind; 

    tmodel.Address  = atmodel; 
    tmodel.AddressList = amodel; 
    return View(tmodel); 
} 

對於在下拉列表中進行編輯,將顯示值列表。但不顯示選定的值。什麼是我的代碼中的錯誤。任何建議。

編輯:

@Html.DropDownListFor(model => model.State, new SelectList(Model.RegionList, "ID", "Name",Model.State)) 

回答

1

假設AddressList屬性是一個IList<Something>嘗試這樣的:

@for (var i = 0; i < Model.AddressList.Count; i++) 
{ 
    @Html.DropDownListFor(
     model => model.AddressList[i].State, 
     new SelectList(Model.Address.RegionList, "Value", "Text") 
    ) 
} 
+0

model.AddressList [I] .STATE值不填充在列表中的值之一,它不顯示爲選擇的值。 – kk1076

2

model => item.State 

是行不通的,因爲它從html幫手隱藏fa ct下拉的值取自模型。實現這個正確的方法是用for替換foreach

@for (int i=0; i<Model.AddressList.Count; i++) 
{ 
    @Html.DropDownListFor(model => model.AddressList[i].State, new SelectList(Model.Address.RegionList, "Value", "Text", Model.Address.RegionList.SelectedValue))          
} 
+0

item.State值已填充,但model.AddressList [i] .state未填充 – kk1076

+0

@ kk1076,這聽起來有點奇怪,因爲它們基本上都是相同的東西。 – Andrei