I have an ASP.NET Core MVC web project with 4 pages.
The first page is a kind of login. Two text fields with a Next button. The second page shows data about the logged in person and contains two more text fields (mail address and date). Both of them must be filled.
On the page there is a Next button. If you click on this button, the personal data and the values from the two text fields should be displayed on the 3 page overview page (readonly fields). If you recognize an error from the two text fields, then you can navigate back to page 2 via the Back button and correct it.
And here is my problem. I can't get back to the 2 page because in the controller in the HttpPost (IActionResult PersonData)
the ModelState.IsValid
is true because I don't have an error in the ModelState
, but how can I navigate back to the 2 page? The ModelState.IsValid
, in the IActionResult
, is also used to redirect to page 3.
What am I doing wrong?
public IActionResult Login()
{
ViewData["Title"] = _localizer["Login"];
return View();
}
public IActionResult PersonData()
{
ViewData["Title"] = _localizer["Persondata"].Value;
model.PersonName = "Firstname Lastname";
model.Street= "Street123";
model.Zip = "12345";
model.City= "Tokio";
return View(model);
}
[HttpPost]
public ActionResult PersonData(PersonDataModel personDataModel)
{
ViewData["Title"] = _localizer["Persondata"].Value;
if (ModelState.IsValid)
{
return RedirectToAction("Overview", personDataModel);
}
return View("Persondata", personDataModel);
}
public IActionResult Overview(PersonDataModel personDataModel)
{
ViewData["Title"] = _localizer["Overview"].Value;
model = persondataModel;
return View("Overview", personDataModel);
}
Next button in PersonData.cshtml
:
<button type="submit" class="btn btn-primary">Next</button>
Next and Back Button in Overview.cshtml
:
<button type="submit" class="btn btn-primary">@HtmlLocalizer["Back"]</button>
@*go back to PersonData page with actual model values*@
</form>
<form asp-action="Confirmation" asp-controller="Statistics" method="post" class="needs-validation" novalidate>
<button type="submit" class="btn btn-primary">@HtmlLocalizer["Confirmation"]</button>
@*go forward to Confirmation.cshtml*@
</form>
Thank you.
To solve the issue, I suggest you could add a new parameter like back which means the back button return to the previous page, inside the post method, you could check it and decide which view it should go to.
The view like this:
<input type="hidden" name="back" value="true" />
....
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
Action method:
[HttpPost]
public async Task<IActionResult> Create( TblUsed tblUsed, bool back)
Result: