Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC return a different view

Tags:

c#

asp.net-mvc

I have a view which contains a form, the form posts and the data gets processed etc, then I want to return the view Index, so return view("Index");

however this will then complain about my ViewData not existing, I get the feeling that the controller code under Index() isn't being processed which adds the list it requires to the ViewData, anyone know what's wrong?

Thanks

edit: Apparently it's done to prevent recursion.. in which case, I'm lost as to what to do without repeating all my ViewData stuff both Controllers

like image 213
Tablet Avatar asked Nov 25 '08 14:11

Tablet


People also ask

Can we return multiple view in MVC?

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.

How do I navigate to another view in MVC?

You can use the RedirectToAction() method, then the action you redirect to can return a View. The easiest way to do this is: return RedirectToAction("Index", model); Then in your Index method, return the view you want.

How do I return a view from a different controller?

Just add your View to the Shared subdirectory and you're good to go. If you do return View("~/Views/Wherever/SomeDir/MyView. aspx") You can return any View you'd like.

What does return View () in MVC do?

View discovery The default behavior of the View method ( return View(); ) is to return a view with the same name as the action method from which it's called. For example, the About ActionResult method name of the controller is used to search for a view file named About. cshtml .


2 Answers

I think you should have two actions: one that processes the form submission, and another one that collects data for the view. Once the form has been processed, you call return RedirectToAction("Index") and you are done. I hope I understood what you meant by this.

like image 114
CodeClimber Avatar answered Oct 12 '22 17:10

CodeClimber


If your Index method on the controller does a return View("Index"); then just call the Index method with any parameters it requires. Then the method will populate the ViewData reuired by the Index View.

like image 36
Matthew Avatar answered Oct 12 '22 18:10

Matthew