【问题标题】:How to specify default Area to Html.BuildUrlFromExpression call如何为 Html.BuildUrlFromExpression 调用指定默认区域
【发布时间】:2011-06-08 21:47:50
【问题描述】:

我有类似link text 的问题

我所有的链接都是这样的:htp//site/controller/action/id

我刚刚添加了名为 BackEnd 的区域。

我的控制器:

[ActionLinkArea("")]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
}

现在,当我尝试使用

获取一些控制器 URL 时
@Html.ActionLink<HomeController >(c => c.Index(), "Home") 

一切正常,网址为 htp://site/HomeController/Index/

但是当我使用 Microsoft.Web.Mvc.dll 的扩展方法时

 @Html.BuildUrlFromExpression<HomeController>(c => c.Index())

我得到 URL htp://site/BackEnd/HomeController/Index/

如何使用 BuildUrlFromExpression 获取没有区域的 URL 以及为什么 ActionLink 可以正常工作但 BuildUrlFromExpression 没有?

【问题讨论】:

  • 我刚刚反汇编了Microsoft.Web.Mvc,发现这段代码VirtualPathData virtualPath = routeCollection.GetVirtualPath(context, routeValuesFromExpression);其中 routeCollection abd context - 我们从 HtmlHelper 获得,而 routeValuesFromExpression - 从带有 Area 的表达式返回值,但 routeValuesFromExpression 具有正常值。
  • 我找到了答案:aspnet.codeplex.com/workitem/7764 该方法在内部使用 LinkBuilder.BuildUrlFromExpression()。后者调用 routeCollection.GetVirtualPath(context, routeValues) 而不是 routeCollection.GetVirtualPathForArea(context, routeValues);使用区域时导致无效结果。

标签: c# asp.net-mvc-3 razor


【解决方案1】:

这是微软的错误。

http://aspnet.codeplex.com/workitem/7764

该方法在内部使用 LinkBuilder.BuildUrlFromExpression()。后者调用 routeCollection.GetVirtualPath(context, routeValues) 而不是 routeCollection.GetVirtualPathForArea(context, routeValues);使用区域时导致无效结果。

我做到了,方法返回正确的 URL

【讨论】:

    【解决方案2】:

    我有更好的答案!

    public static string Image<T>(this HtmlHelper helper, Expression<Action<T>> action, int width, int height, string alt)
                where T : Controller
        {
            var expression = action.Body as MethodCallExpression;
            string actionMethodName = string.Empty;
            if (expression != null)
            {
                actionMethodName = expression.Method.Name;
            }
            string url = new UrlHelper(helper.ViewContext.RequestContext, helper.RouteCollection).Action(actionMethodName, typeof(T).Name.Remove(typeof(T).Name.IndexOf("Controller"))).ToString();         
            //string url = LinkBuilder.BuildUrlFromExpression<T>(helper.ViewContext.RequestContext, helper.RouteCollection, action);
            return string.Format("<img src=\"{0}\" width=\"{1}\" height=\"{2}\" alt=\"{3}\" />", url, width, height, alt);
        }
    
    <%=Html.Image<ClassController>(c => c.Index(), 120, 30, "Current time")%>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-18
      • 1970-01-01
      • 1970-01-01
      • 2011-11-24
      • 1970-01-01
      • 2013-10-03
      • 2015-02-02
      • 1970-01-01
      相关资源
      最近更新 更多