Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return different views in a controller

If I have a controller and I want to return a view based on what my conditional logic goes to, is that possible? I have different types of models that i want to insert into a view DEPENDING on my conditional logic (if statements) Can i do this? and how would I do this

like image 593
anthonypliu Avatar asked Mar 20 '11 07:03

anthonypliu


People also ask

CAN controller return multiple views?

You can only return one value from a function so you can't return multiple partials from one action method. If you are trying to return two models to one view, create a view model that contains both of the models that you want to send, and make your view's model the new ViewModel. E.g. Save this answer.

How do I return a view from a controller?

How to return a view from controller action method? To return a view from the controller action method, we can use View() method by passing respective parameters. return View(“ViewName”) – returns the view name specified in the current view folder (view extension name “. cshtml” is not required.

How do I return a partial view to another controller?

How to return a partial view from controller action method? To return a Partial view from the controller action method, we can write return type as PartialViewResult and return using PartialView method.


2 Answers

Sure, return View() accepts a view name as its first parameter. Just specify a different view.

If you have different models that go into the same view, either try to merge them, create a container-model (one property per model type and then an enum so that the views know what to render), use dynamic as the model in the view, or create one view per model.

The first and last would be my preferred choice, but it depends on the specifics.

like image 92
Michael Stum Avatar answered Sep 19 '22 23:09

Michael Stum


You can do something like that in your controller (this is an example looking if a user is autheticated)

if (Request.IsAuthenticated)
    return View("View1", new AuthenticatedViewModel(myValues1));
else
    return View("View2", new AnonymousViewModel(myValues2));
like image 41
Iridio Avatar answered Sep 18 '22 23:09

Iridio