2010-01-19 30 views
0

我在部分頁面中使用自定義HtmlHelper。從部分頁面獲取當前操作名稱

例子:

/Home/Index - Is the Main Page with Index View 

/Home/Partial - Is the Partial Action with Partial - A Partial View 

在索引視圖:

Html.RenderAction("Partial"); 

在局部視圖:

我使用一個自定義的HtmlHelper在那的HtmlHelper我需要得到請求來自哪裏的url?

讓的說應該是這樣「/首頁/部分」

我怎樣才能得到這個在我的HtmlHelper方法

回答

6

有幾個方法可以做到這一點取決於你想要什麼。你的HtmlHelper的ViewContext屬性將有隻是您需要了解特定請求的一切:HttpContext的,RequestContext的,的RouteData,TempData的,ViewData的,等

爲了得到要求的電流路徑,嘗試helper.ViewContext.HttpContext.Request.Path。這將返回實際的請求路徑,可能是「/」或「/ home/index」,如果路徑在URL中是顯式的。

我不知道你爲什麼想要「/ home/partial」。由於這是局部視圖,請求總是會來自其他地方,例如。 「/家/索引」。

無論如何,你可以檢查的RouteData並獲得(部分)動作和控制器,其他路由值中:

public static string TestHelper(this HtmlHelper helper) 
{ 
    var controller = helper.ViewContext.RouteData.Values["controller"].ToString(); 
    var action = helper.ViewContext.RouteData.Values["action"].ToString(); 
    return controller + "/" + action; 
} 

如果叫你的索引視圖(Index.aspx的),它會返回「 首頁/索引「。
如果在部分視圖(Partial.aspx)中調用,它將返回「主頁/部分」。

希望有所幫助。