如何在HtmlHelper.GenerateLink方法中生成HtmlAttributes
2012-04-02 16:47 Fred-Xu 阅读(1630) 评论(0) 编辑 收藏 举报在Controller中使用HtmlHelper.GenerateLink方法,生成一段HtmlAttributes,例如:
string opLink = HtmlHelper.GenerateLink(requestContext, System.Web.Routing.RouteTable.Routes,
"订单进程", "Default", "Create", "OrderProcess",
new System.Web.Routing.RouteValueDictionary(new { id = Id }), new { target = "_blank" });
我们如果在前端View页面中调用@Html.ActionLink通常会用:
new { target = "_blank" }
匿名方法来生成这段HtmlAttributes,但是如果在Controller中使用GenerateLink方法,会如下错误:
Error 1 The best overloaded method match for 'System.Web.Mvc.HtmlHelper.GenerateLink(System.Web.Routing.RequestContext, System.Web.Routing.RouteCollection, string, string, string, string, System.Web.Routing.RouteValueDictionary, System.Collections.Generic.IDictionary<string,object>)' has some invalid arguments C:\Users\...
Error 2 Argument 8: cannot convert from 'AnonymousType#1' to 'System.Collections.Generic.IDictionary<string,object>' C:\Users\...
MVC有一个叫做AnonymousObjectToHtmlAttributes 方法,匿名对象转换为HtmlAttributes,把上面的代码改为:
HtmlHelper.AnonymousObjectToHtmlAttributes 方法在指定的 HTML 特性中,将下划线字符 (_) 替换为连字符 (-)。
string opLink = HtmlHelper.GenerateLink(requestContext, System.Web.Routing.RouteTable.Routes,
"订单进程", "Default", "Create", "OrderProcess",
new System.Web.Routing.RouteValueDictionary(new { id = Id }), HtmlHelper.AnonymousObjectToHtmlAttributes(new { target = "_blank" }));
这样就解决了。