[英]return view() for all actions in controller .net mvc
I have one controller HomeController.cs
. 我有一个控制器
HomeController.cs
。
In this controller I have some actions like about,contact etc. 在这个控制器中,我有一些关于,联系等动作。
If I want that will work I have to defined function to each view: 如果我希望它能正常工作,则必须为每个视图定义函数:
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
return View();
}
I want that for all the requests to the controller it will be return the View()
, so I will not have to defined a function to each view. 我希望对于控制器的所有请求都将返回
View()
,因此我不必为每个视图定义一个函数。
*Update I want to know if there is some handler that will work something like this: *更新我想知道是否有一些处理程序可以像这样工作:
protected override void OnActionCall()
{
return View();
}
WARNING: I would strongly advise against this as it pretty much defeats the purpose of using MVC but... 警告:我强烈建议您这样做,因为它几乎违反了使用MVC的目的,但是...
You could create a general action that will find the view for you: 您可以创建一个常规操作,该操作将为您找到视图:
public ViewResult Page(string urlSlug)
{
if (!this.ViewExists(urlSlug))
{
throw new HttpException(404, "Page not found");
}
return this.View(urlSlug);
}
private bool ViewExists(string name)
{
ViewEngineResult result = ViewEngines.Engines.FindView(ControllerContext, name, null);
return (result.View != null);
}
You will need to edit your RouteConfig
though: 但是,您将需要编辑
RouteConfig
:
routes.MapRoute(
name: "Home_Page",
url: "{urlSlug}",
defaults: new { controller = "Home", action = "Page" },
constraints: new { urlSlug = @"[A-Za-z0-9-]{1,50}" }
);
Now if you look for /about
it will look for that view. 现在,如果您查找
/about
,它将查找该视图。 You will run into problems when you want to use Model
data though. 但是,当您要使用
Model
数据时会遇到问题。 I think the time spent asking this question and implementing this solution would take a lot longer than simply having return View()
我认为花时间问这个问题和实施此解决方案将比简单地拥有
return View()
花费更多的时间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.