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.

2

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

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

Comments

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

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.