Return different views in a controller

2019-04-27 23:07发布

问题:

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

回答1:

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.



回答2:

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