我有这个以编程方式填充的列表。
<ul id="topNavigation" class="topNavigation" runat="server"></ul>
这是列表项的代码
foreach (var node in children)
{
HtmlGenericControl li = new HtmlGenericControl("li");
HtmlGenericControl span = new HtmlGenericControl("span");
span.Attributes.Add("class", "editableLinks");
span.Attributes.Add("data-id", node.id.ToString());
var child = new Node(node.id);
if (child.Name.Contains("contact"))
break;
var sortOrder = child.GetProperty("sortOrder");
if (sortOrder != null)
span.Attributes.Add("data-sort", sortOrder.Value);
var hidden = "";
var deleted = "0";
var naviHide = child.GetProperty("umbracoNaviHide");
var userDeleted = child.GetProperty("userDeleted");
if (naviHide != null)
{
hidden = naviHide.Value;
if (userDeleted != null)
deleted = userDeleted.Value;
// nav.InnerText += naviHide.Value;
if (hidden != "1" && deleted !="1")
{
topNavigation.Controls.Add(li);
var anchor = new HyperLink();
var title= child.GetProperty("title");
//anchor.Text=child.Id.ToString();
if (!string.IsNullOrWhiteSpace(title.Value))
span.InnerHtml = title.Value;
else
{
var name = child.Name.Split('_');
span.InnerHtml = name[1];
}
if (child.Id == Node.GetCurrent().Id)
li.Attributes.Add("class", "current");
anchor.CssClass = "navigation";
if (!host.Contains("testcms"))
{
if (!string.IsNullOrWhiteSpace(child.GetProperty("umbracoUrlAlias").Value))
anchor.NavigateUrl = "/"+child.GetProperty("umbracoUrlAlias").Value;
else
anchor.NavigateUrl = child.NiceUrl;
}
else
{
var id = "/" + child.Id.ToString();
anchor.NavigateUrl = id;
//anchor.NavigateUrl=anchor.NavigateUrl.Replace("usercontrols", "");
}
anchor.Controls.Add(span);
li.Controls.Add(anchor);
}
}
有没有办法通过此函数中提取的sortOrder值来排序列表项?目前我正在通过javascript重新排序它,但在一些使用它的地方javascript无法使用。
答案 0 :(得分:0)
我将假设您有一些类型的外部元素,您要添加li
个实例。在这种情况下,您只需要将对象构建到不同的列表中,然后在添加到外部对象之前对其进行排序。您需要为Select
和OrderBy
方法提供LINQ命名空间。
using System.Linq;
// Holder for the data coming out of your internal for each converted
// to a transformation function
class ListNode
{
// or whatever comparable type your sort order is
int SortOrder {get;set;}
HttpGenericControl Li {get; set;}
}
// Convert function is your code inside the foreach returning the
// HttpGenericControl li from each loop same code except for the return
ListNode ConvertChildToLi(ChildClass child)
{
// Same code here to the end of the for loop
return new ListNode { SortOrder = sortOrder, Li = li };
}
然后在你的调用函数中
var liControls = children.Select(ConvertChildToLi).OrderBy(n=> n.SortOrder);
foreach(var li in liControls)
{
// Assuming outer element ul exists
ul.Controls.Add(li);
}