问题是文本包含在ListValues中,所选项应该匹配表达式值。
我有一个几乎完整的解决方案,但我被困在最后一个障碍!
这是我的下拉列表帮助器
// DropDown helper
public static MvcHtmlString DropDownInputFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> ListValues, string DefaultText, object HTMLAttributes, bool CanEdit)
{
if (CanEdit == true)
{
// return a dropdown
return htmlHelper.DropDownListFor(expression, ListValues, DefaultText, HTMLAttributes);
}
else
{
// just return the text (no editor)
return htmlHelper.DisplayFor(expression);
}
}
正如您所看到的,我将根据用户是否可以编辑返回帮助器。在这种情况下,如果他们可以编辑,我们就返回下拉列表,如果他们不能编辑,我们就返回DisplayFor。
然而,这个问题是DisplayFor显示的是"值"(外键),而不是下拉菜单的文本。
关于如何显示文本而不是值有什么建议吗?
我明白,如果CanEdit为false,您只想显示与ListValues中的值相对应的文本。为此,您可以尝试这样做:
// DropDown helper
public static MvcHtmlString DropDownInputFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> ListValues, string DefaultText, object HTMLAttributes, bool CanEdit)
{
if (CanEdit == true)
{
// return a dropdown
return htmlHelper.DropDownListFor(expression, ListValues, DefaultText, HTMLAttributes);
}
else
{
// just return the text (no editor)
//but first make sure you have a valid value in your list and show it
var selected = ListValues.FirstOrDefault(item => item.Selected == true);
if (selected != null)
return htmlHelper.DisplayName(selected.Text);
else
//here you can just put the default selected item if no valid value is found
return htmlHelper.DisplayName(ExpressionHelper.GetExpressionText(expression));//or whatever defaultvalue you want
}
}