Asp.net

使用 ASP.NET MVC 時從 WebForm 訪問 HtmlHelpers

  • January 27, 2022

我正在添加一個 WebForm,我想從中解析到 URL 的路由。例如,在 MVC 中我會使用

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

因此,如果您有辦法從同一個應用程序中的 WebForm 訪問同一個 URL,我們將不勝感激。

在您的網路表單中嘗試這樣的事情:

<% 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" }) %>

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
{

}

}

引用自:https://stackoverflow.com/questions/1274319