做了查看存在于Asp.Net MVC? [英] Does a View Exist in Asp.Net MVC?
本文介绍了做了查看存在于Asp.Net MVC?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有人知道如何,如果有可能,以确定是否一个特定的视图名称从控制器中呈现视图之前存在?
我有个要求,动态地确定对呈现视图的名称。如果视图存在同名那么我需要渲染这一观点。如果用自定义名称没有意见,然后我需要渲染的默认视图。
我想我的控制器内做类似下面的code的内容:
公众的ActionResult指数()
{
变种名称= SomeMethodToGetViewName(); //将ViewExists'的方法是我一直无法找到。
如果(ViewExists(名))
{
retun视图(名);
}
其他
{
返回查看();
}
}
感谢。
解决方案
私人布尔ViewExists(字符串名称)
{
ViewEngineResult结果= ViewEngines.Engines.FindView(ControllerContext,姓名,NULL);
返回(result.View!= NULL);
}
对于那些寻找一个复制/粘贴扩展方法:
公共静态类ControllerExtensions
{
公共静态布尔ViewExists(此控制器控制器,字符串名称)
{
ViewEngineResult结果= ViewEngines.Engines.FindView(controller.ControllerContext,姓名,NULL);
返回(result.View!= NULL);
}
}
Does anybody know how if it's possible to determine if a specific view name exists from within a controller before rendering the view?
I have a requirement to dynamically determine the name of the view to render. If a view exists with that name then I need to render that view. If there is no view by the custom name then I need to render a default view.
I'd like to do something similar to the following code within my controller:
public ActionResult Index()
{
var name = SomeMethodToGetViewName();
//the 'ViewExists' method is what I've been unable to find.
if( ViewExists(name) )
{
retun View(name);
}
else
{
return View();
}
}
Thanks.
解决方案
private bool ViewExists(string name)
{
ViewEngineResult result = ViewEngines.Engines.FindView(ControllerContext, name, null);
return (result.View != null);
}
For those looking for a copy/paste extension method:
public static class ControllerExtensions
{
public static bool ViewExists(this Controller controller, string name)
{
ViewEngineResult result = ViewEngines.Engines.FindView(controller.ControllerContext, name, null);
return (result.View != null);
}
}
这篇关于做了查看存在于Asp.Net MVC?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文