Martin Matoušek
Martin Matoušek

Reputation: 33

Is it possible to render View without create Action in ASP.NET MVC?

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.

Upvotes: 1

Views: 1668

Answers (3)

JotaBe
JotaBe

Reputation: 39014

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.

Upvotes: 3

Maess
Maess

Reputation: 4146

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")

Upvotes: 0

theLaw
theLaw

Reputation: 1291

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

public ActionResult yourView()
{
    return View();
}

Upvotes: 0

Related Questions