我有一个函数填充在ASP.NET MVC中创建下拉列表。
public static MvcHtmlString countryDropDown(this HtmlHelper helper, string name, string optionLabel, object selectedValue)
{
XmlDocument doc = new XmlDocument();
doc.Load(HttpContext.Current.Server.MapPath("~/App_Data/countries.xml"));
StringBuilder b = new StringBuilder();
b.Append(string.Format("<select name=\"{0}\" id=\"{0}\">", name));
if (!string.IsNullOrEmpty(optionLabel))
b.Append(string.Format("<option value=\"\">{0}</option>", optionLabel));
foreach (XmlNode node in doc.SelectNodes("//country"))
{
string selected = string.Empty;
if (node.Attributes["name"].Value == selectedValue as string)
{
selected = "selected=\"selected\"";
}
b.Append(string.Format("<option value=\"{0}\" {2}>{1}</option>", node.Attributes["name"].Value, node.Attributes["name"].Value, selected));
}
b.Append("</select>");
return MvcHtmlString.Create( b.ToString());
}
我在创建和编辑视图中使用此功能:
@Html.countryDropDown("Country"," ", ViewData["Country"])
它完美地显示了国家/地区列表,但问题是我从未在“编辑”页面中选择已保存的值。 如何修改代码以便它可以在编辑页面中选择值。
答案 0 :(得分:0)
使用
解决 @Html.countryDropDown("Country"," ", ViewData.Eval("Country"))
而不是
@Html.countryDropDown("Country"," ", ViewData["Country"]