gpt4 book ai didi

c# MVC Html helper + 表达式 + 去除丑陋

转载 作者:行者123 更新时间:2023-11-30 15:43:40 25 4
gpt4 key购买 nike

我正在尝试使用以下语法从 IList 创建下拉列表:

@Html.DropDowntListFor(Model.VisitingAddresses, vistingAddress => vistingAddress.Id, vistingAddress => vistingAddress.Name)

这适用于以下代码:

public static IHtmlString DropDowntListFor
<TModel>(this HtmlHelper htmlHelper, IList<TModel> list, Expression<Func<TModel, string>> value, Expression<Func<TModel, string>> text)
{
var dropdownName = value.Parameters.First().Name;

var selectedListItem = new List<SelectListItem>();

var values = list.AsQueryable().Select(value).ToList();
var texts = list.AsQueryable().Select(text).ToList();

int i;
for (i = 0; i < values.Count; i++)
{
selectedListItem.Add(new SelectListItem
{
Value = values[i],
Text = texts[i]
});
}

return htmlHelper.DropDownList(dropdownName, selectedListItem);
}

但是如您所见,上面的代码(在 htmlhelper 中)真的很难看,有人知道在 html 帮助程序中使用更漂亮的方式(在代码中)吗?

提前致谢。

最佳答案

你在找这样的东西吗?

public static IHtmlString DropDowntListFor<TModel>
(this HtmlHelper htmlHelper, IList<TModel> list,
Expression<Func<TModel, string>> valueSelector,
Expression<Func<TModel, string>> textSelector)
{
var dropdownName = valueSelector.Parameters.First().Name;

Func<TModel, string> compiledValueSelector = valueSelector.Compile();
Func<TModel, string> compiledTextSelector = textSelector.Compile();

var selectedListItem = list.Select(x => new SelectListItem {
Value = compiledValueSelector(x),
Text = compiledTextSelector(x) })
.ToList();

return htmlHelper.DropDownList(dropdownName, selectedListItem);
}

请注意,如果您不需要文本选择器作为表达式树,您可以进一步稍微简化它:

public static IHtmlString DropDowntListFor<TModel>
(this HtmlHelper htmlHelper, IList<TModel> list,
Expression<Func<TModel, string>> valueSelectorExpression,
Func<TModel, string> textSelector)
{
var dropdownName = valueSelector.Parameters.First().Name;

var valueSelector = valueSelectorExpression.Compile();

var selectedListItem = list.Select(x => new SelectListItem {
Value = valueSelector(x),
Text = textSelector(x) })
.ToList();

return htmlHelper.DropDownList(dropdownName, selectedListItem);
}

关于c# MVC Html helper + 表达式 + 去除丑陋,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6620712/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com