Persisting QueryString parameters when validation error occurs
I have an Upload File form, the file has (Name nvarchar, FileData varbinary(max))
Name and FileData are mandatory fields
For some reason, validation of FileData (using Required attribute) is not working, so I searched the internet and found an Html Helper extension method which renders a Input(file) and can validate it.
But the problem is that when I add the error to the model state and return View()
the returnUrl which was in the query string is gone, how can I persist returnUrl and/or some other query string variables in such case?
You may notice, I can't use RedirectToAction
, I have to return 开发者_如何学CView()
so that the validation summary can show the error (and hopefully, the Name field persists its value).
The short answer is that you can't return a View in the way you'd like and also retain the querystring parameters.
What I would do is store the return URL as part of the view model.
This way when you return View()
you'll have access to the return URL in the model you pass.
This is actually possible (credit to Ivan Korytin). You have to put the parameters as part of the form action (I've enhanced it to simply repeat the query string):
<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);
}
精彩评论