在 ASP.NET MVC 中检索当前视图名称?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1268763/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Retrieve the current view name in ASP.NET MVC?
提问by Dylan Beattie
I have a partial view (control) that's used across several view pages, and I need to pass the name of the current view back to the controller - so if there's e.g. validation errors, I can re-draw the original view.
我有一个跨多个视图页面使用的局部视图(控件),我需要将当前视图的名称传递回控制器 - 因此,如果出现验证错误,我可以重新绘制原始视图。
A workaround way to do it would be (in the controller methods)
一种解决方法是(在控制器方法中)
var viewName = "Details"; // or whatever
ViewData["viewName"] = viewName;
return(View(viewName, customer));
and then in the partial itself, render it as
然后在部分本身中,将其渲染为
<input type="hidden" name="viewName"
value="<%=Html.Encode(ViewData["viewName"])%>" />
Question is - is there some property or syntax I can use to retrieve this directly instead of setting it from the controller? I've tried the obvious:
问题是 - 是否有一些属性或语法可以用来直接检索它而不是从控制器设置它?我已经尝试过显而易见的:
<input type="hidden" name="viewName"
value="<%=Html.Encode(this.Name)%>" />
but this doesn't work. What am I missing here?
但这不起作用。我在这里缺少什么?
Thanks.
谢谢。
采纳答案by Haacked
Well if you don't mind having your code tied to the specific view engine you're using, you can look at the ViewContext.Viewproperty and cast it to WebFormView
好吧,如果您不介意将您的代码绑定到您正在使用的特定视图引擎,您可以查看该ViewContext.View属性并将其转换为WebFormView
var viewPath = ((WebFormView)ViewContext.View).ViewPath;
I believe that will get you the view name at the end.
我相信这会在最后为您提供视图名称。
EDIT:Haacked is absolutely spot-on; to make things a bit neater I've wrapped the logic up in an extension method like so:
编辑:Haacked 绝对是正确的;为了使事情更整洁,我将逻辑包装在一个扩展方法中,如下所示:
public static class IViewExtensions {
public static string GetWebFormViewName(this IView view) {
if (view is WebFormView) {
string viewUrl = ((WebFormView)view).ViewPath;
string viewFileName = viewUrl.Substring(viewUrl.LastIndexOf('/'));
string viewFileNameWithoutExtension = Path.GetFileNameWithoutExtension(viewFileName);
return (viewFileNameWithoutExtension);
} else {
throw (new InvalidOperationException("This view is not a WebFormView"));
}
}
}
which seems to do exactly what I was after.
这似乎正是我所追求的。
回答by Konamiman
I had the same problem and that's how I solved it:
我遇到了同样的问题,这就是我解决它的方法:
namespace System.Web.Mvc
{
public static class HtmlHelperExtensions
{
public static string CurrentViewName(this HtmlHelper html)
{
return System.IO.Path.GetFileNameWithoutExtension(
((RazorView)html.ViewContext.View).ViewPath
);
}
}
}
Then in the view:
然后在视图中:
var name = Html.CurrentViewName();
or simply
或者干脆
@Html.CurrentViewName()
回答by Daniel Elliott
If you just want the action name then this would do the trick:
如果您只想要动作名称,那么这样做就可以了:
public static string ViewName(this HtmlHelper html)
{
return html.ViewContext.RouteData.GetRequiredString("action");
}
回答by Miros
If you want to get the filename from within a partial view, this seems to work:
如果您想从局部视图中获取文件名,这似乎有效:
public static class HtmlHelperExtensions
{
public static string GetViewFileName(this HtmlHelper html, object view)
{
return @"\"+ view.GetType().FullName.Replace("ASP._Page_", "").Replace("_cshtml", ".cshtml").Replace("_", @"\");
}
}
And in the partial view, you should do something like this:
在局部视图中,您应该执行以下操作:
var filename = Html.GetViewFileName(this);
or this:
或这个:
@Html.GetViewFileName(this)
Please do comment if this is not a good approach - any alternatives?
如果这不是一个好方法,请发表评论 - 有其他选择吗?
回答by Mahib
Easiest solution is using ViewBag.
最简单的解决方案是使用 ViewBag。
public ActionResult Index()
{
ViewBag.CurrentView = "Index";
return View();
}
On the cshtml page
在 cshtml 页面上
@{
var viewName = ViewBag.CurrentView;
}
Or,
或者,
((RazorView)ViewContext.View).ViewPath
回答by Postlagerkarte
If you are looking for solution for asp.net core you can use:
如果您正在寻找 asp.net core 的解决方案,您可以使用:
@System.IO.Path.GetFileNameWithoutExtension(ViewContext.View.Path)
This will return the current view name.
这将返回当前视图名称。
回答by Damon Jones
I had the same issue recently and the snippet of code I came up with solved my issue.
我最近遇到了同样的问题,我想出的代码片段解决了我的问题。
The only downfall is that Request.UrlReferrer could be null in some cases. Bit late but seemed to work for me and I covered all the bases of Request.UrlReferrer not being null.
唯一的缺点是 Request.UrlReferrer 在某些情况下可能为 null。有点晚了,但似乎对我有用,我涵盖了 Request.UrlReferrer 不为空的所有基础。
if (Request.UrlReferrer != null)
{
var viewUrl = Request.UrlReferrer.ToString();
var actionResultName = viewUrl.Substring(viewUrl.LastIndexOf('/'));
var viewNameWithoutExtension = actionResultName.TrimStart('/');
}
回答by griegs
Shouldn't you be using a validation method like Nerd Dinner implements?
您不应该使用像 Nerd Dinner 工具那样的验证方法吗?
That way you don't actually need to do all this and you can just return the View.
这样你实际上不需要做所有这些,你可以只返回视图。
回答by Anthony Johnston
Just wrote a blog thingy about this
刚刚写了一篇关于这个的博客
http://www.antix.co.uk/A-Developers-Blog/Targeting-Pages-with-CSS-in-ASP.NET-MVC
http://www.antix.co.uk/A-Developers-Blog/Targeting-Pages-with-CSS-in-ASP.NET-MVC
/// <summary>
/// <para>Get a string from the route data</para>
/// </summary>
public static string RouteString(
this ViewContext context, string template) {
foreach (var value in context.RouteData.Values) {
template = template.Replace(string.Format("{{{0}}}",
value.Key.ToLower()),
value.Value == null
? string.Empty
: value.Value.ToString().ToLower());
}
return template;
}
usage
用法
<body class="<%= ViewContext.RouteString("{controller}_{action}") %>">
EDIT : Yes this is not going to give you the view name as the first comment states, it gives you the controller and action. But leaving it here as its valuable to know that it doesn't.
编辑:是的,这不会像第一条评论所说的那样为您提供视图名称,它为您提供控制器和操作。但是把它留在这里是有价值的,知道它没有。

