The following are two examples of a controller for submitting data. One returns the input model if validation fails the other doesn’t. Can someone enlighten me on which is method correct or preferred? They seem to behave exactly the same.
With returning model
[HttpPost]
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
//do stuff
}
return View(model);
}
Without returning model
[HttpPost]
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
//do stuff
}
return View();
}
Usually you want the user to show an error message if the data he submitted is not valid (e.g. he did not enter a valid email address into a field that requries to be an email – see MVC ModelValidation for more information).
You use the ModelState.IsValid to check for that. In this case you usually show him the page he came from (“Register”) and you also want to show the data he entered into the form fields (= RegisterModel). But you want to display an errormessage that tells him what fields are not correct.
If the user’s data is correct and your action succeeds (in this case he was registered successfully) you usually do not show him the registration form again, but you would redirect him to a success page.
Here is a simple example how to validate, show errors and redirect after successfull action.
Example from your code:
On the Register view (Ifno – if you have a strongly typed view, you can use the HTML Helper overloads for that – e.g. use Html.LabelFor, TextboxFor etc methods):
Show general error message/summary;
Show error message next to the inputs: