开发者

Persisting QueryString parameters when validation error occurs

开发者 https://www.devze.com 2023-03-15 10:36 出处:网络
I have an Upload File form, the file has (Name nvarchar, FileData varbinary(max)) Name and FileData are mandatory fields

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);
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号