Here's a running theory of what is happening but since you didn't post all the code I'm only guessing.
1) You do a GET request to Index
which fills ViewBag
and then renders the HTML. This works.
2) You do a POST request to Index
when the user clicks the submit button. This calls your Index
action attributed with HttpPost
which then updates the backend as you'd expect.
3) You return from this action using return View()
4) Your app blows up.
The issue is that on a POST the only data sent back to the server is the data inside the <form>
element, if any. This is generally converted to a model passed to your action. When you then return View()
it is going to try to access ViewBag
but there is no data there because you never added anything. ViewBag
is per request so on the post it has been wiped.
You need to modify all actions that ultimately will render this view to have all of them set up ViewBag
just like you're doing in your initial GET Index
action. This is one reason why using ViewBag
is not really recommended.
//Your Index action called when the user "submits" their data
[HttpPost]
public IActionResult Index( MyModel model )
{
//Do back end work
...
//Have to set ViewBag back up
ViewBag.Modelos = _context.Modelos.ToList();
ViewBag.Estaciones = _context.Estacions.ToList();
ViewBag.Correcciones = _context.Correccions.ToList();
return View();
}
This is also why it is generally recommended that you instead follow the PRG pattern (Post-Redirect-Get). This solves the problem you're seeing but also the infamous browser refresh problem. In this pattern the user POSTs (submits) to the server to update data. The server responds with a redirect request to the browser after saving the data (can be back to the same action), the browser then does a GET request which pulls the updated data.
//Your Index action called when the user "submits" their data
[HttpPost]
public IActionResult Index( MyModel model )
{
//Do back end work
...
return RedirectToAction(nameof(Index));
}
Note that in the case of errors where you want to display the same view again (so the user sees any model errors) then you still need to restore ViewBag
otherwise you're back in the same boat.