ASP.Net MVC探索之路 减少Html.RouteLink或Url.RouteUrl使用次数

本文没什么技术含量,正适合放在目前状况下的博客园首页。

首先定义一条路由规则:

        string[] controllerNamespaces = new string[] { "Web.Controllers" };
        routes.MapRoute(
            
"Details",
            
"Details/{productId}",
            
new {controller="Product", action="Details"},
            
new {productId = @"\d+" },
            controllerNamespaces
        );


以前生成链接是这么做的:

        foreach (var item in Model) {
            Writer.Write(Html.RouteLink(item.Title, 
"Details"new { ProductId=item.ProductId}));
        }

现在改为这样了:
        string detailsLinkFormat = Html.RouteLink("{1}""Details"new { ProductId=0 })
            .ToString().Replace(
"0""{0}");
        StringBulder sb 
= new StringBuilder(Model.Count());
        
foreach (var item in Model) {
            sb.Append(
string.Format(detailsLinkFormat,item.ProductId,item.Title));
        }
        Writer.Write(sb.ToString());

首先生成一个链接地址:
<a href="/Details/0">{1}</a>

将“0”替换成“{0}”后就成了这样:
<a href="/Details/{0}">{1}</a>

然后我们根据这个格式去生成新的链接地址即可。

简洁起见,以上代码没进行Model空校验、Url编码处理、Html编码处理、列表格式化等。

另,老赵以前专门做过关于Url生成性能的分析
原文地址:https://www.cnblogs.com/alby/p/1900900.html