在网上看了有说把ActionLink扩展成类似于@Html.ActionLink<T>(T=>T.Index(...))这种写法的,于是就自己写了一个
代码写的不是很好,仅供参考:
public static void ActionLink<T>(this HtmlHelper helper, Expression<Func<T, ActionResult>> expression,string linkText, object paras=null) where T : Controller
{
var para = expression.Parameters[0] as ParameterExpression;
var controller = para.Type.Name.Replace("Controller", "");
var action = (expression.Body as MethodCallExpression).Method.Name;
var linkUrl = string.Format("/{0}/{1}", controller, action);
if (paras != null)
{
linkUrl += "?";
Type paratype = paras.GetType();
PropertyInfo[] propers = paratype.GetProperties();
foreach (var item in propers)
{
var paraname = item.Name;
var paraVal = item.GetValue(paras);
linkUrl += paraname + "=" + paraVal;
linkUrl += "&";
}
linkUrl = linkUrl.TrimEnd('&');
string linkHtmltag = string.Format("<a href='{0}'>{1}</a>", linkUrl, linkText);
HttpContext.Current.Response.Write(linkHtmltag);
}
}
如果谁有更好的办法可以留言一下,谢谢!