代码之家  ›  专栏  ›  技术社区  ›  oglester

使用ASP.NET MVC时从WebForm访问HTMLHelpers

  •  7
  • oglester  · 技术社区  · 15 年前

    我正在添加一个WebForm,从中可以解析到URL的路由。例如,在MVC中,我只使用

    return RedirectToAction("Action", "Controller");
    

    所以,如果你有一种方法从同一个应用程序中的一个webform获得相同的URL,那将是非常感谢的。

    3 回复  |  直到 12 年前
        1
  •  15
  •   eu-ge-ne    15 年前

    在您的Web表单中尝试类似的操作:

    <% var requestContext = new System.Web.Routing.RequestContext(
           new HttpContextWrapper(HttpContext.Current),
           new System.Web.Routing.RouteData());
       var urlHelper = new System.Web.Mvc.UrlHelper(requestContext); %>
    
    <%= urlHelper.RouteUrl(new { controller = "Controller", action = "Action" }) %>
    
        2
  •  4
  •   Lynn Eriksen    12 年前

    为pagecommon修改了以上代码的版本…因为现在它坏了。

    public static class MvcPages{
    public static UrlHelper GetUrlHelper(this System.Web.UI.Control c)
    {
        var helper = new System.Web.Mvc.UrlHelper(c.Page.Request.RequestContext);
        return helper;
    }
    
    public static HtmlHelper GetHtmlHelper(this System.Web.UI.Control c)
    {
        var httpContext = new HttpContextWrapper(HttpContext.Current);
        var controllerContext = new ControllerContext(httpContext, new RouteData(), new DummyController());
        var viewContext = new ViewContext(controllerContext, new WebFormView(controllerContext, "View"), new ViewDataDictionary(), new TempDataDictionary(), TextWriter.Null);
    
        var helper = new HtmlHelper(viewContext, new ViewDataBag());
        return helper;
    } 
    
    private class ViewDataBag : IViewDataContainer
    {
        ViewDataDictionary vdd = new ViewDataDictionary();
        public ViewDataDictionary ViewData
        {
            get
            {
                return vdd;
            }
            set
            {
                vdd = value;
            }
        }
    }
    
    private class DummyController : Controller
    {
    
    }
    
    }
    
        3
  •  0
  •   Maslow    12 年前

    对于那些在页面中寻找实际的htmlhelper或更清洁的方法来使用urlhelper的用户:

    public static class PageCommon
    {
        public static System.Web.Mvc.UrlHelper GetUrlHelper(this System.Web.UI.Control c)
        {
            var helper = new System.Web.Mvc.UrlHelper(c.Page.Request.RequestContext);
            return helper;
        }
        class ViewDataBag : IViewDataContainer
        {
            ViewDataDictionary vdd = new ViewDataDictionary();
            public ViewDataDictionary ViewData
            {
                get
                {
                    return vdd;
                }
                set
                {
                    vdd = value;
                }
            }
        }
        public static System.Web.Mvc.HtmlHelper GetHtmlHelper(this System.Web.UI.Control c)
        {
    
            var v = new System.Web.Mvc.ViewContext();
            var helper = new System.Web.Mvc.HtmlHelper(v, new ViewDataBag());
            return helper;
        }
    }