检索ASP.NET MVC当前视图的名字吗? [英] Retrieve the current view name in ASP.NET MVC?

查看:264
本文介绍了检索ASP.NET MVC当前视图的名字吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个局部视图(控制)这是在多个视图页面使用,我需要通过当前视图的名称回控制器 - 所以如果有如验证错误,我可以重新绘制的原始视图。

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?

感谢。

推荐答案

那么,如果你不介意你的code依赖于你所使用的特定视图引擎,你可以看看 ViewContext.View 属性和它转换为 WebFormView

Well if you don't mind having your code tied to the specific view engine you're using, you can look at the ViewContext.View property and cast it to WebFormView

var viewPath = ((WebFormView)ViewContext.View).ViewPath;

我相信,将让你在最后的视图名称。

I believe that will get you the view name at the end.

编辑: Haacked是绝对现货上;做事情有点整洁,我裹逻辑在扩展方法如下所示:

Haacked is absolutely spot-on; to make things a bit neater I've wrapped the logic up in an extension method like so:

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.

这篇关于检索ASP.NET MVC当前视图的名字吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆