我的任务是对组合框不区分大小写的产品列表进行排序。
在视图文件中:
@Html.DropDownListFor(m => m.ProductId, ViewData["Products"] as SelectList,
@Resources.App_GlobalResources.Resource.Common_SelectItem)
在控制器中,我尝试了2个实现:
1)
var products = new SelectList(GetProducts().OrderBy(a => a, new CaseInsensitiveComparer()),
"id", "name", selectedProductId);
ViewData["Products"] = products;
public class CaseInsensitiveComparer : IComparer<Product>
{
public int Compare(Product productX, Product productY)
{
return string.Compare(productX.Name,productY.Name,StringComparison.OrdinalIgnoreCase);
}
}
2)
var orderedProducts = GetProducts().OrderBy(p => p.Name.ToLower()).ToList();
var products = new SelectList(orderedProducts, "id", "name", selectedProductId)
ViewData["Products"] = products;
预期:列出已排序不区分大小写的内容 现在:列出已排序区分大小写的
但是任何实现都无法按预期工作。有任何想法吗?提前谢谢。
答案 0 :(得分:0)
尝试创建自己的帮助程序进行排序:
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" }
)