香草柠檬 发表于 2013-1-3 17:30:25

Mvc扩展Html.ActionLink(强类型扩展)

<div id="cnblogs_post_body">在网上看了有说把ActionLink扩展成类似于@Html.ActionLink<T>(T=>T.Index(...))这种写法的,但是按照他们的代码写都没有试成功,于是就自己写了一个,但是只支持
@{Html.ActionLink<T>(T=>T.Index(...));}这种写法,因为@Html.ActionLink<T>(T=>T.Index(...))这种写法会报错,具体是什么原因也不清楚。
代码写的不是很好,仅供参考:

    public static void ActionLink<T>(this HtmlHelper helper, Expression<Action<T>> Action, string linkname, dynamic para) where T : class
      {
            string lamda = Action.ToString();
            string lamexp = lamda.Substring(lamda.IndexOf('.') + 1);
            string action = lamexp.Substring(0, lamexp.IndexOf('('));
            string controller = helper.ViewContext.RouteData.Values["controller"].ToString();
            StringBuilder builder = new StringBuilder();
            builder.AppendFormat("<ahref='/{0}/{1}", controller, action);
            if (para != null)
            {
                var props = para.GetType().GetProperties();
                builder.Append("?");
                foreach (var item in props)
                {
                  string paraName = item.Name;
                  object paraVal = item.GetValue(para, null);
                  builder.AppendFormat("{0}={1}", paraName, paraVal);
                  builder.Append("&");
                }
                builder.Remove(builder.Length - 1, 1);
            }
            builder.Append("'>");
            builder.Append(linkname);
            builder.Append("</a>");
            HttpContext.Current.Response.Write(builder.ToString());
      }
如果谁有更好的办法可以留言一下,谢谢!
页: [1]
查看完整版本: Mvc扩展Html.ActionLink(强类型扩展)