替代使用Request.URL和Request.URLReferrer得到在MVC当前的链接? [英] Alternative to using Request.URL and Request.URLReferrer to get the current link in MVC?
问题描述
我希望写在我的 BaseController
类中的方法/属性,这将使任何行动来获得当前的URL。如果我称之为本地主机/关键字/编辑/ 1
我可以使用 Request.Url
来获得url。但是,如果在我的编辑视图的局部视图,我需要使用 Request.UrlReferrer
获得本地主机/关键字/编辑/ 1
。如果我使用 Request.Url
,而在局部视图的动作,我最终会与本地主机/关键字/ PartialView
。
I was hoping to write a method/property in my BaseController
class that would enable any action to get the current URL. If I call localhost/Keyword/Edit/1
I can use Request.Url
to get the url. However, if there is a partial view in my Edit view, I need to use Request.UrlReferrer
to get localhost/Keyword/Edit/1
. If I use Request.Url
while in the action for the partial view, I would end up with localhost/Keyword/PartialView
.
有一个内置的方式总是获取URL,这将是在浏览器地址栏不论我是否在视图或局部视图?我
Is there a built in way to always get the Url that would be in the browser address bar regardless of whether I'm in a View or Partial View?
推荐答案
创建一个自定义HtmlHelper.Your的HtmlHelper的ViewContext属性将有只是您需要了解特定请求的一切:HttpContext的,RequestContext的,的RouteData,TempData的,ViewData的,等等。
Create a custom HtmlHelper.Your HtmlHelper's ViewContext property will have just about everything you need about the particular request: HttpContext, RequestContext, RouteData, TempData, ViewData, etc.
要获得请求的当前路径,尝试 helper.ViewContext.HttpContext.Request.Path
To get the current path of the request, try helper.ViewContext.HttpContext.Request.Path
您可以检查的RouteData并获得(部分)动作和控制器,其他航线中值:
You can check the RouteData and obtain the (partial) action and controller, among other route values:
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;
}
如果叫你的索引视图,它会返回首页/索引。
If called in your Index view , it would return "Home/Index".
如果叫你的局部视图,它会返回首页/部分。
If called in your Partial view , it would return "Home/Partial".
希望有所帮助。
这篇关于替代使用Request.URL和Request.URLReferrer得到在MVC当前的链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!