How can I preserve the url (with the querystring) after an Http Post but also add an error to the Model State?
Ivan Korytin's answer was the best (and only answer I could find which seemed to actually work properly without using hidden field hacks) which I've improved a little with Request.QueryString
.
You have to put the parameters as part of the form action:
<form action="@Url.Action("CreateEntity", "Employee")?@(Request.QueryString)"
enctype="multipart/form-data" method="POST">
When you perform the following the query string (and GET
parameters) are now preserved:
[HttpPost]
public ActionResult MyAction(MyAction model)
{
if (!ModelState.IsValid)
{
return View(model);
}
Your second scenario doesn't have the model state because when you do a redirection the browser makes a separate request to that location, separate requests = new model state.
I would suggest using your first scenario and place a "ReturnUrl" in your model and render it to the client as a hidden field.
//In your model add the ReturnUrl Property
public class AuthenticatModel
{
public string Account {get; set;}
public string SocialSecurityNumber {get;set;}
public string ReturnUrl {get;set;}
}
ModelState.AddModelError("Authenticated", authenticationError);
//Set the return URL property before returning the view
model.ReturnUrl = returnUrl;
return View(model);
@* add the return URL as a hidden field to your view so it can be posted back *@
@Html.HiddenFor(model => model.ReturnUrl)