How to specify a default value for the Html.BuildUrlFromExpression scope

I have a problem like link text

All my links look like this: htp // site / controller / action / id

I just added an area called BackEnd .

My controller:

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

Now when I try to get the consortium url using

 @Html.ActionLink<HomeController >(c => c.Index(), "Home") 

Everything works fine, and url is htp: // site / HomeController / Index /

But when I use the extension method from Microsoft.Web.Mvc.dll

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

I get the URL htp: // site / BackEnd / HomeController / Index /

How can I get a URL without a scope using BuildUrlFromExpression, and why does ActionLink work fine, but you don't use the BuildUrlFromExpression expression?

+4
source share
2 answers

This is a Microsoft bug.

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

The method uses internally LinkBuilder.BuildUrlFromExpression (). The latter calls routeCollection.GetVirtualPath (context, routeValues) instead of routeCollection.GetVirtualPathForArea (context, routeValues); leading to invalid results when using areas.

I did this and the method returned the correct URL

+3
source

I better answer!

 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")%> 
+2
source

Source: https://habr.com/ru/post/1334336/


All Articles