30

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

2 Answers 2

59

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.

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

4 Comments

+1 absolutely the way to go, read en.wikipedia.org/wiki/Post/Redirect/Get for more details on benefits of this approach.
how about without redirecting? return View("Index")
@CodeClimber. I have a bit similar scenario. I have a partial view in Index page. Partial view submits the form. on form submission data is stored in database. I want to show the latest data on the Index page. when i tried your approach i get this error "The model item passed into the dictionary is of type 'System.Collections.Generic.List but the dictionary requires a model item of type 'UnderstandingPartialViews.Models.abc'"
@Luckyy, we can redirect to action from one controller to another too, via by RedirectToAction
6

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.

Comments

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.