我正在尝试在我的应用程序中的下拉列表中实现编辑和更新。下拉列表的值列表将从模型中显示。但所选值不会显示在下拉列表中。所选值也将作为下拉列表中的值列表填充。
我的模特:
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))
答案 0 :(得分:2)
此
model => item.State
不会起作用,因为它从html帮助器中隐藏了从模型中获取下拉值的事实。实现此目的的正确方法是将foreach
替换为for
:
@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))
}
答案 1 :(得分: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")
)
}