protected void HandleUnauthorizedRequest(ref AuthorizationContext filterContext)
        {
            UrlHelper urlHelper = null;
            if (filterContext.Controller is Controller)
            {
                urlHelper = ((Controller)filterContext.Controller).Url;
            }
            else
            {
                urlHelper = new UrlHelper(filterContext.RequestContext);
            }

            bool isAjaxRequest = filterContext.RequestContext.HttpContext.Request.IsAjaxRequest();

            Func<string, JsonResult> setResult = delegate(string msg)
            {
                DataResultBoolean response = new DataResultBoolean()
                {
                    IsValid = false,
                    Message = msg,
                    MessageType = DataResultMessageType.Error,
                    Data = false
                };
                JsonResult result = new JsonResult();
                result.Data = response;
                return result;
            };

            if (!this.CheckSessionExpired(filterContext.HttpContext))
            {
                if (isAjaxRequest)
                {
                    filterContext.Result = setResult($customNamespace$.Resources.General.GeneralTexts.SessionExpired);
                }
                else
                {
                    filterContext.Result = new RedirectResult(ErrorUrlHelper.SessionExpired(urlHelper));
                }
            }

            // break execution in case a result has been already set
            if (filterContext.Result != null)
                return;

            if (!this.CheckIsAutohrized(filterContext.HttpContext))
            {
                if (isAjaxRequest)
                {
                    filterContext.Result = setResult($customNamespace$.Resources.General.GeneralTexts.PermissionDenied);
                }
                else
                {
                    filterContext.Result = new RedirectResult(ErrorUrlHelper.UnAuthorized(urlHelper));
                }
            }
        }
 private static string BuildNextLink(
     UrlHelper urlHelper, QueryOptions queryOptions, string actionName)
 {
     if (queryOptions.CurrentPage != queryOptions.TotalPages)
     {
         return string.Format(
             "<a href=\"{0}\">Next <span aria-hidden=\"true\">&rarr;</span></a>",
             urlHelper.Action(actionName, new
             {
                 SortOrder = queryOptions.SortOrder,
                 SortField = queryOptions.SortField,
                 CurrentPage = queryOptions.CurrentPage + 1,
                 PageSize = queryOptions.PageSize
             }));
     }
     else
     {
         return string.Format(
             "<a href=\"{0}\" class=\"disabled\">Next <span aria-hidden=\"true\">&rarr;</span></a>",
             urlHelper.Action(actionName, new
             {
                 SortOrder = queryOptions.SortOrder,
                 SortField = queryOptions.SortField,
                 CurrentPage = queryOptions.CurrentPage + 1,
                 PageSize = queryOptions.PageSize
             }));
     }
 }
		public void SetUp()
		{
			string siteRoot = GetSiteRoot();
			string viewPath = Path.Combine(siteRoot, "RenderingTests\\Views");
			Layout = null;
			PropertyBag = new Hashtable(StringComparer.InvariantCultureIgnoreCase);
			Helpers = new HelperDictionary();
			StubMonoRailServices services = new StubMonoRailServices();
			services.UrlBuilder = new DefaultUrlBuilder(new StubServerUtility(), new StubRoutingEngine());
			services.UrlTokenizer = new DefaultUrlTokenizer();
			UrlInfo urlInfo = new UrlInfo(
				"example.org", "test", "/TestBrail", "http", 80,
				"http://test.example.org/test_area/test_controller/test_action.tdd",
				Area, ControllerName, Action, "tdd", "no.idea");
			StubEngineContext = new StubEngineContext(new StubRequest(), new StubResponse(), services,
													  urlInfo);
			StubEngineContext.AddService<IUrlBuilder>(services.UrlBuilder);
			StubEngineContext.AddService<IUrlTokenizer>(services.UrlTokenizer);
			StubEngineContext.AddService<IViewComponentFactory>(ViewComponentFactory);
			StubEngineContext.AddService<ILoggerFactory>(new ConsoleFactory());
			StubEngineContext.AddService<IViewSourceLoader>(new FileAssemblyViewSourceLoader(viewPath));
			

			ViewComponentFactory = new DefaultViewComponentFactory();
			ViewComponentFactory.Service(StubEngineContext);
			ViewComponentFactory.Initialize();

			ControllerContext = new ControllerContext();
			ControllerContext.Helpers = Helpers;
			ControllerContext.PropertyBag = PropertyBag;
			StubEngineContext.CurrentControllerContext = ControllerContext;


			Helpers["urlhelper"] = Helpers["url"] = new UrlHelper(StubEngineContext);
			Helpers["htmlhelper"] = Helpers["html"] = new HtmlHelper(StubEngineContext);
			Helpers["dicthelper"] = Helpers["dict"] = new DictHelper(StubEngineContext);
			Helpers["DateFormatHelper"] = Helpers["DateFormat"] = new DateFormatHelper(StubEngineContext);


			//FileAssemblyViewSourceLoader loader = new FileAssemblyViewSourceLoader(viewPath);
//			loader.AddAssemblySource(
//				new AssemblySourceInfo(Assembly.GetExecutingAssembly().FullName,
//									   "Castle.MonoRail.Views.Brail.Tests.ResourcedViews"));

			viewEngine = new AspViewEngine();
			viewEngine.Service(StubEngineContext);
			AspViewEngineOptions options = new AspViewEngineOptions();
			options.CompilerOptions.AutoRecompilation = true;
			options.CompilerOptions.KeepTemporarySourceFiles = false;
			ICompilationContext context = 
				new CompilationContext(
					new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory),
					new DirectoryInfo(siteRoot),
					new DirectoryInfo(Path.Combine(siteRoot, "RenderingTests\\Views")),
					new DirectoryInfo(siteRoot));

			List<ICompilationContext> compilationContexts = new List<ICompilationContext>();
			compilationContexts.Add(context);
			viewEngine.Initialize(compilationContexts, options);
		}
        public static MvcHtmlString ActionImage(this HtmlHelper html, string action, string controllerName, object routeValues, string imagePath, string alt, string confirmMessage, bool newWindow)
        {
            var url = new UrlHelper(html.ViewContext.RequestContext);

            // build the <img> tag
            var imgBuilder = new TagBuilder("img");
            imgBuilder.MergeAttribute("src", url.Content(imagePath));
            imgBuilder.MergeAttribute("alt", alt);
            string imgHtml = imgBuilder.ToString(TagRenderMode.SelfClosing);

            // build the <a> tag
            var anchorBuilder = new TagBuilder("a");
            anchorBuilder.MergeAttribute("href", url.Action(action, controllerName, routeValues));
            anchorBuilder.InnerHtml = imgHtml; // include the <img> tag inside

            if (!string.IsNullOrEmpty(confirmMessage))
                anchorBuilder.MergeAttribute("onclick", "return confirm('" + confirmMessage + "')");

            if (newWindow)
                anchorBuilder.MergeAttribute("target", "_blank");

            string anchorHtml = anchorBuilder.ToString(TagRenderMode.Normal);

            return MvcHtmlString.Create(anchorHtml);
        }
    public static MvcHtmlString ImageLink(this HtmlHelper html, string action, string controller, object routeValues, string imageURL, string hoverImageURL, string alternateText, object linkHtmlAttributes, object imageHtmlAttributes)
    {
        // Create an instance of UrlHelper
        UrlHelper url = new UrlHelper(html.ViewContext.RequestContext);
        // Create image tag builder
        TagBuilder imageBuilder = new TagBuilder("img");
        // Add image attributes
        imageBuilder.MergeAttribute("src", imageURL);
        imageBuilder.MergeAttribute("alt", alternateText);
        imageBuilder.MergeAttribute("title", alternateText);

        //support for hover
        imageBuilder.MergeAttribute("onmouseover", "this.src='" + hoverImageURL + "'");
        imageBuilder.MergeAttribute("onmouseout", "this.src='" + imageURL + "'");
        imageBuilder.MergeAttribute("border", "0");

        imageBuilder.MergeAttributes(new RouteValueDictionary(imageHtmlAttributes));
        // Create link tag builder
        TagBuilder linkBuilder = new TagBuilder("a");
        // Add attributes
        linkBuilder.MergeAttribute("href", url.Action(action, controller, new RouteValueDictionary(routeValues)));
        linkBuilder.InnerHtml = imageBuilder.ToString(TagRenderMode.SelfClosing);
        linkBuilder.MergeAttributes(new RouteValueDictionary(linkHtmlAttributes));
        // Render tag
        return MvcHtmlString.Create(linkBuilder.ToString(TagRenderMode.Normal));
    }
        public static MvcHtmlString MenuItemCheveron(this HtmlHelper htmlHelper,
                                                     string text, string action, string controller,
                                                     string cheveronText, string area = null)
        {
            var li = new TagBuilder("li");
            var routeData = htmlHelper.ViewContext.RouteData;

            var currentAction = routeData.GetRequiredString("action");
            var currentController = routeData.GetRequiredString("controller");
            var currentArea = routeData.DataTokens["area"] as string;
            var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext, htmlHelper.RouteCollection);

            if (string.Equals(currentAction, action, StringComparison.OrdinalIgnoreCase) &&
                string.Equals(currentController, controller, StringComparison.OrdinalIgnoreCase) &&
                string.Equals(currentArea, area, StringComparison.OrdinalIgnoreCase))
            {
                li.AddCssClass("active");
            }
            var linkBuilder = new TagBuilder("a");
            linkBuilder.MergeAttribute("href", urlHelper.Action(action, controller));

            var htmlText = li.ToString(TagRenderMode.StartTag);
            htmlText += linkBuilder.ToString(TagRenderMode.StartTag);
            htmlText += text;
            htmlText += linkBuilder.ToString(TagRenderMode.EndTag);
            htmlText += li.ToString(TagRenderMode.EndTag);
            return MvcHtmlString.Create(htmlText.ToString());
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="SitemapPingerService"/> class.
 /// </summary>
 /// <param name="loggingService">The logging service.</param>
 /// <param name="urlHelper">The URL helper.</param>
 public SitemapPingerService(
     ILoggingService loggingService,
     UrlHelper urlHelper)
 {
     this.loggingService = loggingService;
     this.urlHelper = urlHelper;
     this.httpClient = new HttpClient();
 }
        public Breadcrumb()
        {
            this.IsVisible = false;

            UrlHelper urlHelper = new UrlHelper(System.Web.HttpContext.Current.Request.RequestContext);
            this.BreadcrumbPaths = new List<KeyValuePair<string, string>>();
            this.BreadcrumbPaths.Add(new KeyValuePair<string, string>(GeneralTexts.Home, HomeUrlHelper.Home_Index(urlHelper)));
        }
        public static MvcHtmlString Favicon(this HtmlHelper helper)
        {
            UrlHelper uh = new UrlHelper(helper.ViewContext.RequestContext);

            string faviconUrl = uh.Content("~/Images/favicon.ico");

            return new MvcHtmlString(string.Format("<link href=\"{0}\" rel=\"shortcut icon\" type=\"image/x-icon\" />", faviconUrl));
        }
        public void RequestContextProperty() {
            // Arrange
            RequestContext requestContext = new RequestContext(new Mock<HttpContextBase>().Object, new RouteData());
            UrlHelper urlHelper = new UrlHelper(requestContext);

            // Assert
            Assert.AreEqual(requestContext, urlHelper.RequestContext);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="SitemapService" /> class.
 /// </summary>
 /// <param name="cacheService">The cache service.</param>
 /// <param name="loggingService">The logging service.</param>
 /// <param name="urlHelper">The URL helper.</param>
 public SitemapService(
     ICacheService cacheService,
     ILoggingService loggingService,
     UrlHelper urlHelper)
 {
     this.cacheService = cacheService;
     this.loggingService = loggingService;
     this.urlHelper = urlHelper;
 }
		public void Setup()
		{
			var controllerContext = new ControllerContext();
			var engineContext = new StubEngineContext { CurrentControllerContext = controllerContext, UrlInfo = new UrlInfo("", "home", "index", "", "") };

			helper = new UrlHelper(engineContext) { UrlBuilder = new DefaultUrlBuilder() };
			helper.UrlBuilder.UseExtensions = false;
			controllerContext.Helpers.Add(helper);
		}
        public void SetUp()
        {
            _serviceProxy = new Mock<ServiceProxy>();

            var type = typeof (ServiceProxy);
            type.SetFieldValue("_instance", _serviceProxy.Object);

            _urlHelper = new UrlHelper();
        }
Exemple #14
0
        public static MvcHtmlString ActionLinkImage(this HtmlHelper htmlHelper, string imageLocation, string altTag, string actionName, string controllerName, RouteValueDictionary routeValues, IDictionary<string, object> htmlAttributes)
        {
            var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext, htmlHelper.RouteCollection);

            var link = new TagBuilder("a");
            link.MergeAttribute("href", urlHelper.Action(actionName, controllerName, routeValues));
            link.MergeAttribute("target", (string)htmlAttributes["target"]); htmlAttributes.Remove("target");
            link.InnerHtml = htmlHelper.Image(imageLocation, altTag, htmlAttributes).ToString();

            return MvcHtmlString.Create(link.ToString(TagRenderMode.Normal));
        }
		public void UrlHelper_ButtonLink_Should_JavaScript_Escape_URLs()
		{
			var controllerContext = new ControllerContext();
			var engineContext = new StubEngineContext { CurrentControllerContext = controllerContext, UrlInfo = new UrlInfo("", "home", "index", "", "") };

			var helper = new UrlHelper(engineContext);
			helper.UrlBuilder = new DefaultUrlBuilder(new StubServerUtility(), null);
			helper.UrlBuilder.UseExtensions = false;
			controllerContext.Helpers.Add(helper);
			
			Assert.AreEqual("<button type=\"button\" onclick=\"javascript:window.location.href = '/MyController/MyAction?ProductName=Jack\\'s+Mine'\">MyButton</button>", helper.ButtonLink("MyButton", DictHelper.CreateN("controller", "MyController").N("action", "MyAction").N("queryString", "ProductName=Jack's Mine")));
		}
 private static string BuildPreviousLink(UrlHelper urlHelper, QueryOptions queryOptions, string actionName)
 {
     return string.Format(
     "<a href=\"{0}\"><span aria-hidden=\"true\">&larr;</span> Previous</a>",
     urlHelper.Action(actionName, new
     {
         SortOrder = queryOptions.SortOrder,
         SortField = queryOptions.SortField,
         CurrentPage = queryOptions.CurrentPage - 1,
         PageSize = queryOptions.PageSize
     }));
 }
Exemple #17
0
 static JsHttpHandler( )
 {
     operations =  new Dictionary<string, OperationDelegate>
     {
         { "Route", (name, context)=>{
             var Url = new UrlHelper(context);
             return Url.RouteUrl(name, new { locale = System.Threading.Thread.CurrentThread.CurrentCulture.Name });
         }},
         { "Resx", (name, context)=>{
             return LocalizationResx.ResourceManager.GetString(name, LocalizationResx.Culture);
         }}
     };
 }
    public static MvcHtmlString BuildKnockoutSortableLink(this HtmlHelper htmlHelper,
        string fieldName, string actionName, string sortField)
    {
        var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);

        return new MvcHtmlString(string.Format(
            "<a href=\"{0}\" data-bind=\"click: pagingService.sortEntitiesBy\"" +
            " data-sort-field=\"{1}\">{2} " +
            "<span data-bind=\"css: pagingService.buildSortIcon('{1}')\"></span></a>",
            urlHelper.Action(actionName),
            sortField,
            fieldName));
    }
        public static MvcHtmlString LinkEntity(this HtmlHelper html, Type type, string action, object id, object text)
        {
            //<a href="type/action/id">type.Name</a>

            var urlHelper = new UrlHelper(html.ViewContext.RequestContext);

            var builder = new TagBuilder("a");
            builder.MergeAttribute("href", urlHelper.Action(action, type.Name, new { Id = id }));
            builder.SetInnerText(text.ToString());

            string Html = builder.ToString(TagRenderMode.Normal);

            return MvcHtmlString.Create(Html);
        }
        /// <summary>
        /// Creates the appropriate li and anchor tags for use inside of the skeleton tabs.
        /// </summary>
        /// <param name="this">Instance of HtmlHelper being extended.</param>
        /// <param name="tabText">The text displayed on the tab.</param>
        /// <param name="activeControllerName">Name of the active controller.  This is used to determine which anchor tag in
        /// the tabs gets the 'active' css class.</param>
        /// <returns></returns>
        public static MvcHtmlString Tab(this HtmlHelper @this, string tabText, string activeControllerName)
        {
            var text = String.IsNullOrEmpty(tabText) ? "My Tasks" : tabText;
            var controllerName = String.IsNullOrEmpty(activeControllerName) ? "Tasks" : activeControllerName;

            var url = new UrlHelper(@this.ViewContext.RequestContext);
            var link = new Element("a").AddAttribute("href", url.Action("Index", controllerName)).Update(tabText);

            var currentController = @this.ViewContext.RequestContext.RouteData.Values["controller"].ToString();
            if (controllerName.Equals(currentController, StringComparison.OrdinalIgnoreCase))
                link.CssClasses.Add("active");

            return MvcHtmlString.Create(new Element("li", link));
        }
        public static UrlHelper CreateUrlHelper(RouteCollection routes, string currentAppRelativePath = "~/")
        {
            var httpContextMock = new Mock<HttpContextBase>();
             httpContextMock.Setup(c => c.Request.ApplicationPath).Returns("");
             httpContextMock.Setup(c => c.Request.AppRelativeCurrentExecutionFilePath).Returns(currentAppRelativePath);
             httpContextMock.Setup(c => c.Response.ApplyAppPathModifier(It.IsAny<string>())).Returns<string>(s => s);

             RouteData routeData = routes.GetRouteData(httpContextMock.Object);

             var requestContext = new RequestContext(httpContextMock.Object, routeData);
             var urlHelper = new UrlHelper(requestContext, routes);

             return urlHelper;
        }
        public override void OnException(ExceptionContext filterContext)
        {
            base.OnException(filterContext);

            string LogTitle = string.Format("{0} {1}", MvcApplication.Name, LoggerCategories.UIServerSideUnhandledException);
            NameValueCollection serverVars = System.Web.HttpContext.Current.Request.ServerVariables;
            Dictionary<string, object> param = (from key in serverVars.AllKeys select new KeyValuePair<string, object>(key, serverVars[key])).ToDictionary(k => k.Key, k => k.Value);
            LoggingHelper.Write(new LogEntry(filterContext.Exception, LoggerCategories.UIServerSideUnhandledException, 1, 1, TraceEventType.Error, LogTitle, param));

            if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
            {
                JsonResult jr = new JsonResult()
                {
                    Data = new DataResultString()
                                    {
                                        Message = $customNamespace$.Resources.General.GeneralTexts.UnexpectedError,
                                        IsValid = false,
                                        Data = $customNamespace$.Resources.General.GeneralTexts.UnexpectedError,
                                        MessageType = DataResultMessageType.Error
                                    }
                };

                filterContext.Result = jr;
                filterContext.ExceptionHandled = true;
            }
            else
            {
                UrlHelper url = new UrlHelper(filterContext.RequestContext);
                RedirectResult r = null;
                Type exceptionType = filterContext.Exception.GetType();
                if (exceptionType == typeof(FaultException))
                {
                    r = new RedirectResult(string.Format("{0}?id={1}", ErrorUrlHelper.FaultExceptionUnExpected(url), filterContext.Exception.Message));
                }
                else
                {
                    if (exceptionType.Namespace == typeof(Endpoint).Namespace)
                    {
                        r = new RedirectResult(ErrorUrlHelper.CommunicationError(url));
                    }
                    else
                    {
                        r = new RedirectResult(ErrorUrlHelper.UnExpected(url));
                    }
                }

                filterContext.Result = r;
                filterContext.ExceptionHandled = true;
            }
        }
Exemple #23
0
        public static MvcHtmlString Image(this HtmlHelper htmlHelper, string imageLocation, string altTag, IDictionary<string, object> htmlAttributes)
        {
            var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext, htmlHelper.RouteCollection);

            if (string.IsNullOrEmpty(imageLocation))
                throw new ArgumentException("Value cannot be null or empty.", "imageLocation");

            var image = new TagBuilder("img");
            image.MergeAttributes<string, object>(htmlAttributes);
            image.MergeAttribute("src", urlHelper.Content(imageLocation));
            image.MergeAttribute("alt", htmlHelper.Encode(altTag));

            return MvcHtmlString.Create(image.ToString(TagRenderMode.SelfClosing));
        }
        public void Url_DelegatesToChildPage() {
            // Arrange
            MockViewStartPage viewStart = new MockViewStartPage();
            var viewPage = new Mock<WebViewPage>() { CallBase = true };
            var helper = new UrlHelper(new RequestContext());
            viewPage.Object.Url = helper;
            viewStart.ChildPage = viewPage.Object;

            // Act
            var result = viewStart.Url;

            // Assert
            Assert.AreSame(helper, result);
        }
 public static MvcHtmlString BuildSortableLink(this HtmlHelper htmlHelper, string fieldName, string actionName, string sortField, QueryOptions queryOptions)
 {
     var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
     var isCurrentSortField = queryOptions.SortField == sortField;
     return new MvcHtmlString(string.Format("<a href=\"{0}\">{1} {2}</a>", urlHelper.Action(actionName,
     new
     {
         SortField = sortField,
         SortOrder = (isCurrentSortField
     && queryOptions.SortOrder == SortOrder.ASC)
     ? SortOrder.DESC : SortOrder.ASC
     }),
     fieldName,
     BuildSortIcon(isCurrentSortField, queryOptions)));
 }
Exemple #26
0
 /// <summary>
 /// 创建主页实体
 /// </summary>
 /// <returns></returns>
 public static UrlHelper Instance()
 {
     if (_instance == null)
     {
         lock (lockObject)
         {
             if (_instance == null)
             {
                 _instance = new UrlHelper();
             }
         }
     }
     urlHelper = new System.Web.Mvc.UrlHelper(new RequestContext(new HttpContextWrapper(HttpContext.Current), new RouteData()));
     return _instance;
 }
    public static MvcHtmlString BuildKnockoutNextPreviousLinks(this HtmlHelper htmlHelper, string actionName)
    {
        var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);

        return new MvcHtmlString(string.Format(
"<nav>" +
"    <ul class=\"pager\">" +
"        <li data-bind=\"css: pagingService.buildPreviousClass()\">" +
"           <a href=\"{0}\" data-bind=\"click: pagingService.previousPage\">Previous</a></li>" +
"        <li data-bind=\"css: pagingService.buildNextClass()\">" +
"           <a href=\"{0}\" data-bind=\"click: pagingService.nextPage\">Next</a></li></li>" +
"    </ul>" +
"</nav>",
        @urlHelper.Action(actionName)
        ));
    }
    public static MvcHtmlString Action(this UrlHelper helper, string actionName, string controllerName, bool generateToken)
    {
        var rvd = new RouteValueDictionary();
        if (generateToken)
        {
            // Call the generateUrlToken method which create the hash
            var token = TokenUtility.GenerateUrlToken(string.Empty, actionName, rvd, "@#123%#");

            // The hash is added to the route value dictionary
            rvd.Add("urltoken", token);
        }

        // the link is formed by using the GenerateLink method.
        var link = new UrlHelper(helper.RequestContext).Action(actionName, controllerName, rvd);
        var mvcHtmlString = MvcHtmlString.Create(link);
        return mvcHtmlString;
    }
 public static MvcHtmlString BuildNextPreviousLinks(
     this HtmlHelper htmlHelper, QueryOptions queryOptions, string actionName)
 {
     var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
     return new MvcHtmlString(string.Format(
      "<nav>" +
      "    <ul class=\"pager\">" +
      "      <li class=\"previous {0}\">{1}</li>" +
      "      <li class=\"next {2}\">{3}</li>" +
      "    </ul>" +
      "</nav",
     IsPreviousDisabled(queryOptions),
     BuildPreviousLink(urlHelper, queryOptions, actionName),
     IsNextDisabled(queryOptions),
     BuildNextLink(urlHelper, queryOptions, actionName)
     ));
 }
Exemple #30
0
    public static MvcHtmlString ActionImage(this HtmlHelper html, string action, string routeV, string imagePath, string alt, string args)
    {
        var url = new UrlHelper(html.ViewContext.RequestContext);

            // build the <img> tag
            var imgBuilder = new TagBuilder("img");
            imgBuilder.MergeAttribute("src", url.Content(imagePath));
            imgBuilder.MergeAttribute("alt", alt);
            string imgHtml = imgBuilder.ToString(TagRenderMode.SelfClosing);

            // build the <a> tag
            var anchorBuilder = new TagBuilder("a");
            anchorBuilder.MergeAttribute("href", url.Action(action, routeV) + args);
            anchorBuilder.InnerHtml = imgHtml; // include the <img> tag inside
            string anchorHtml = anchorBuilder.ToString(TagRenderMode.Normal);

            return MvcHtmlString.Create(anchorHtml);
    }
 /// <summary>
 /// Invoke regulated action to know if the request can be honored.
 /// </summary>
 /// <typeparam name="TController">Controller that contains the action.</typeparam>
 /// <param name="helper">Helper representation of @Url.</param>
 /// <param name="action">Action on which rights will be tested.</param>
 /// <returns>String representation of the controller action URL.</returns>
 public static string RegulatedAction <TController>(this UrlHelper helper, Expression <Action <TController> > action)
 {
     return(helper.RegulatedAction(action, null, null, null));
 }
        /// <summary>
        /// Invoke regulated action to know if the request can be honored.
        /// </summary>
        /// <typeparam name="TController">Controller that contains the action.</typeparam>
        /// <param name="helper">Helper representation of @Url.</param>
        /// <param name="action">Action on which rights will be tested.</param>
        /// <param name="routeValues">Additional route value params.</param>
        /// <returns>String representation of the controller action URL.</returns>
        public static string RegulatedAction <TController>(this UrlHelper helper, Expression <Action <TController> > action, object routeValues)
        {
            var routeValueDictionnary = new RouteValueDictionary(routeValues);

            return(helper.RegulatedAction(action, routeValueDictionnary, null, null));
        }