Consider the following code snippet. GuestResponse
is just a class with some properties as a data model.
When visitors invokes localhost\home\RsvpForm
the controller return View without data passed to it so the visitors get a blank HTML form.
After populating the form partially (just for simulating the case IsValid=false
), the visitors submit the form back to the server. The server checks the validity of the data, in this case, it is invalid so the server returns View()
.
What I don't understand is why return View();
rather than return View(gr);
still preserves previous filled data? How does the View get the previous filled data when we don't pass model data when invoking return View();
?
Controller
public class HomeController : Controller
{
[HttpGet]
public ViewResult RsvpForm()
{
return View();
}
[HttpPost]
public ViewResult RsvpForm(GuestResponse gr)
{
if (ModelState.IsValid)
{
return View("ThankYou", gr);
}
else
{
return View();// rather than return View(gr);
}
}
}
View
@model PartyInvites.Models.GuestResponse
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<body>
@using (Html.BeginForm())
{
@Html.ValidationSummary()
Your name: @Html.TextBoxFor(x => x.Name)
... other controls go here ...
<input type="submit" value="Submit RSVP" />
}
</body>
</html>