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
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 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 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.
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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With