Asp.net mvc 项目在组合框(SelectList)中不区分大小写排序
我的任务是对组合框中的产品项列表进行排序,不区分大小写 在视图文件中:Asp.net mvc 项目在组合框(SelectList)中不区分大小写排序,asp.net-mvc,linq,entity-framework,razor,Asp.net Mvc,Linq,Entity Framework,Razor,我的任务是对组合框中的产品项列表进行排序,不区分大小写 在视图文件中: @Html.DropDownListFor(m => m.ProductId, ViewData["Products"] as SelectList, @Resources.App_GlobalResources.Resource.Common_SelectItem) 在controller中,我尝试了两种实现: 一, 应为:列表排序不区分大小写 现在:列表区分大小写 但是,任何
@Html.DropDownListFor(m => m.ProductId, ViewData["Products"] as SelectList,
@Resources.App_GlobalResources.Resource.Common_SelectItem)
在controller中,我尝试了两种实现:
一,
应为:列表排序不区分大小写
现在:列表区分大小写
但是,任何实现都不能像预期的那样工作。有什么想法吗?提前感谢。尝试创建自己的帮助程序进行排序:
public static class HtmlExtensions
{
public static IHtmlString DropDownListForSorted<TModel, TProperty>(
this HtmlHelper<TModel> helper,
Expression<Func<TModel, TProperty>> expression,
IEnumerable<SelectListItem> items,
object htmlAttributes
)
{
var model = helper.ViewData.Model;
var orderedItems = items.OrderBy(x => x.Text); // or x => x.Value
return helper.DropDownListFor(
expression,
new SelectList(orderedItems, "Value", "Text"),
htmlAttributes
);
}
}
如果它没有按预期工作,1它是如何工作的,2它的预期是什么?我已经更新了问题您的代码对我来说很好。您确定由于接收数据的顺序而无法获得此结果吗?不确定in会产生任何影响,但您可以这样做。OrderBy p=>p.Name,StringComparer.OrdinalIgnoreCase,因此您不需要自制的比较器。这似乎是不必要的?你为什么不把一个排序过的列表传递给标准的下拉列表呢?是的,你可以这样做。但您必须传递SelectListItem的排序列表。这就是为什么这个助手很有用。我已经更新了代码,将排序从x.Value更改为x.Text
var orderedProducts = GetProducts().OrderBy(p => p.Name.ToLower()).ToList();
var products = new SelectList(orderedProducts, "id", "name", selectedProductId)
ViewData["Products"] = products;
public static class HtmlExtensions
{
public static IHtmlString DropDownListForSorted<TModel, TProperty>(
this HtmlHelper<TModel> helper,
Expression<Func<TModel, TProperty>> expression,
IEnumerable<SelectListItem> items,
object htmlAttributes
)
{
var model = helper.ViewData.Model;
var orderedItems = items.OrderBy(x => x.Text); // or x => x.Value
return helper.DropDownListFor(
expression,
new SelectList(orderedItems, "Value", "Text"),
htmlAttributes
);
}
}
@Html.DropDownListForSorted(
x => x.SelectedItem,
Model.Items,
new { id = "mylist" }
)