2

我正在尝试在我的应用程序的下拉列表中实现编辑和更新。下拉列表的值列表从模型中显示。但所选值未显示在下拉列表中。所选值也作为下拉列表中的值列表填充。

我的模型:

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))
4

2 回答 2

2

这个

model => item.State

不会起作用,因为它从 html 帮助器中隐藏了下拉列表的值是从模型中获取的事实。实现这一点的正确方法是替换foreachfor

@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))                                     
}
于 2013-08-07T12:18:00.097 回答
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")
    )
}
于 2013-08-07T12:16:01.757 回答