1

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 Dec 12 '13 at 15:39
  • possible duplicate of [Simple ASP.NET MVC views without writing a controller](http://stackoverflow.com/questions/3008970/simple-asp-net-mvc-views-without-writing-a-controller) – haim770 Dec 12 '13 at 15:44

3 Answers3

3

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.

JotaBe
  • 38,030
  • 8
  • 98
  • 117
0

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")
Maess
  • 4,118
  • 20
  • 29
  • You need to give the name of the partial as the first argument, and then pass in the model directly as Model if it needs a model. – Maess Dec 12 '13 at 15:33
0

In my opinion it's not possible, the least you can create is

public ActionResult yourView()
{
    return View();
}
theLaw
  • 1,261
  • 2
  • 11
  • 23