使用MVCSiteMapProvider中的自定义路径数据构建自定义URL

时间:2012-12-11 09:08:33

标签: c# asp.net-mvc mvcsitemapprovider

我们正在为我们的网站使用MVCSiteMapProvider。

这是场景...... 想象一下员工的页面/employee/123。这将包含员工详细信息以及需要在网址中维护123的一组链接。

某些链接需要指向遗留网址,因此像/demographics/?employeeID=123这样的网址就是一个例子。这些链接中大约有30个,因此在站点地图中维护这些链接势在必行。

有关如何处理此问题的任何建议都会有所帮助。

1 个答案:

答案 0 :(得分:1)

您可以创建DynamicNodeProvider来处理此方案。您只需在循环时添加“相关”节点,以便它们全部显示在一起。 id存储在RouteValues中并为所有用户缓存,因此站点地图不会在请求之间忘记它。

public class EmployeeDynamicNodeProvider
    : DynamicNodeProviderBase
{
    CRUDExample db = new CRUDExample();

    public override IEnumerable<DynamicNode> GetDynamicNodeCollection(ISiteMapNode node)
    {
        var result = new List<DynamicNode>();

        var employees = db.Employee;
        foreach (var employee in employees)
        {
            var employeeKey = "Product_" + employee.Id.ToString();

            // Create the "Details" node for the employee
            var employeeNode = new DynamicNode(employeeKey, "EmployeeParentNodeKey", employee.Name, employee.Name, "Employee", "Details");

            // Set the "id" route value so the match will work.
            employeeNode.RouteValues.Add("id", employee.Id);

            // Add the node to the result
            result.Add(employeeNode);


            // Create the "Edit" node for the employee
            var employeeEditNode = new DynamicNode("EmployeeEdit_" + employee.Id.ToString(), employeeKey, "Edit", "Edit", "Employee", "Edit");

            // Set the "id" route value of the edit node
            employeeEditNode.RouteValues.Add("id", employee.Id);

            // Add the node to the result
            result.Add(employeeEditNode);


            // Create the "Delete" node for the employee
            var employeeDeleteNode = new DynamicNode("EmployeeDelete_" + employee.Id.ToString(), employeeKey, "Delete", "Delete", "Employee", "Delete");

            // Set the "id" route value of the delete node
            employeeDeleteNode.RouteValues.Add("id", employee.Id);

            // Add the node to the result
            result.Add(employeeDeleteNode);


            // Create the "Demographics" node for the employee
            var employeeDemographicsNode = new DynamicNode("EmployeeDemographics_" + employee.Id.ToString(), employeeKey, "Demographics", "Demographics", "Employee", "Demographics");

            // Set the "id" route value of the delete node
            employeeDemographicsNode.RouteValues.Add("id", employee.Id);

            // Add the node to the result
            result.Add(employeeDemographicsNode);
        }

        return result;
    }
}

对于URL,System.Web.Routing将路由值转换为URL。但是,如果您的网址很复杂,还有其他几种选择:

  1. 使用站点地图节点的Url属性,而不是路由值。
  2. 创建自定义网址解析程序以处理网址的特殊情况。