Is it possible to get/render View without creating Action in Controller? I have many Views where I dont need pass any model or viewbag variables and I thing, its useless to create only empty Actions with names of my Views.
-
Using what Url pattern you want to access those Views?haim770– haim7702013-12-12 15:39:41 +00:00Commented Dec 12, 2013 at 15:39
-
possible duplicate of Simple ASP.NET MVC views without writing a controllerhaim770– haim7702013-12-12 15:44:40 +00:00Commented Dec 12, 2013 at 15:44
3 Answers
You could create a custom route, and handle it in a generic controller:
In your RouteConfig.cs:
routes.MapRoute(
"GenericRoute", // Route name
"Generic/{viewName}", // URL with parameters
new { controller = "Generic", action = "RenderView", }
);
And then implement a controller like this
public GenericContoller : ...
{
public ActionResult RenderView(string viewName)
{
// depending on where you store your routes perhaps you need
// to use the controller name to choose the rigth view
return View(viewName);
}
}
Then when a url like this is requested:
http://..../Generic/ViewName
The View, with the provided name will be rendered.
Of course, you can make variations of this idea to adapt it to your case. For example:
routes.MapRoute(
"GenericRoute", // Route name
"{controller}/{viewName}", // URL with parameters
new { action = "RenderView", }
);
In this case, all your controllers need to implement a RenderView, and the url is http://.../ControllerName/ViewName.
Comments
If these views are partial views that are part of a view that corresponds to an action, you can use @Html.Partial in your main view to render the partial without an action.
For example:
@Html.Partial("MyPartialName")