我在访问Html.DropdownList的选定值中的文本字段时遇到问题。
我的ViewModel是
public class UserViewModel
{
public List<SelectListItem> SupportedCurrency
{
get;
set;
}
public string DefaultCurrency
{
get;
set;
}
}
我的控制器按下面的方式填充下拉列表。
public List<SelectListItem> GetSupportedCurrencies(string setupValue)
{
List<SelectListItem> items = new List<SelectListItem>();
try
{
IList<Currency> currencyList = Helper.GetFormattedCurrenciesList(CurrenciesService.GetSupportedCurrencies());
foreach (Currency c in currencyList)
{
if (!string.IsNullOrEmpty(setupValue) && c.CurrencyCode.Equals(setupValue))
{
items.Add(new SelectListItem
{
Text = c.CurrencyDescription,
Value = c.CurrencyCode,
Selected = true
});
}
else
{
items.Add(new SelectListItem
{
Text = c.CurrencyDescription,
Value = c.CurrencyCode
});
}
}
}
catch (Exception ex)
{
throw ex
}
return items;
}
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Index()
{
userViewData.SupportedCurrency = GetSupportedCurrencies(userModelData.DefaultCurrency);
SelectList SupportedCurrencyList = new SelectList(userViewData.SupportedCurrency, "CurrencyCode", "CurrencyDescription");
.........
}
在查看索引中 &lt;%= Html.DropDownList(“userViewModel.DefaultCurrency”,Model.SupportedCurrency)%&gt;
......................
当我发布/更新时,我会调用不同的操作(比如更新),我想访问Currencycode和CurrencyDescription。我可以获得Currencycode,但我无法访问CurrencyDescription。
非常感谢任何帮助。
答案 0 :(得分:0)
描述(<option>
s的文本)未从下拉列表(<select>
元素)的表单中发布。您可以做的是在服务器上维护描述到值的映射,以便快速查找。或者您可以简单地将描述用于SelectListItem
对象的文本和值。
答案 1 :(得分:0)
我建议这样做:
public List<SelectListItem> GetSupportedCurrencies()
{
List<SelectListItem> items = new List<SelectListItem>();
try
{
IList<Currency> currencyList = Helper.GetFormattedCurrenciesList(CurrenciesService.GetSupportedCurrencies());
foreach (Currency c in currencyList)
{
items.Add(new SelectListItem
{
Text = c.CurrencyDescription,
Value = c.CurrencyCode
});
}
}
catch (Exception ex)
{
throw ex
}
return items;
}
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Index()
{
userViewData.SupportedCurrency = GetSupportedCurrencies();
SelectList SupportedCurrencyList = new SelectList(userViewData.SupportedCurrency, "Value", "Text", userModelData.DefaultCurrency);
.........
}