2009-08-13 44 views
6

我正在添加一個WebForm,我想從中解析到URL的路由。例如,在MVC我只想用使用ASP.NET MVC從WebForm訪問HtmlHelpers

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

所以,如果你在同一個應用程序一個WebForm獲取到同一URL的方式,我們將不勝感激。

+0

你需要UrlHelper的實例,不是的HtmlHelper – 2009-08-13 20:39:42

+3

試試這個:http://stackoverflow.com/questions/724153/how-do-i-construct-a-route-without-viewcontext-in-asp -net-mvc – 2009-08-13 20:41:16

回答

15

嘗試這樣的事情在你的網上表格:

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

對於那些尋找一個實際的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; 
    } 
} 
+0

這對我來說並不成功。我創建了PageCommon類。然後我在MasterPage.master上添加了片段。 '<%= this.GetHtmlHelper()。部分(「錯誤」)%>'並且收到一個ArgumentNullException。 – 2015-05-18 23:47:43

3

修訂的代碼版本上面的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 
{ 

} 

} 
+0

這對我來說並不成功。我創建了類MvcPages。然後我在MasterPage.master上添加了片段。 '<%= this.GetHtmlHelper()。部分(「錯誤」)%>'並且收到一個InvalidOperationException異常。 – 2015-05-18 23:41:24