Access HtmlHelpers from WebForm when using ASP.NET MVC

前端 未结 3 1546
鱼传尺愫
鱼传尺愫 2020-12-10 16:24

I am adding a WebForm from which I would like to resolve routes to URLs. For example, in MVC I would just use

return RedirectToAction(\"Action\", \"Control         


        
3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-10 17:07

    Revised version of the code above for PageCommon ... as it currently is it breaks.

    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
    {
    
    }
    
    }
    

提交回复
热议问题