开发者

ASP.NET MVC how to reset form when action returns a FileResult?

开发者 https://www.devze.com 2022-12-21 18:03 出处:网络
I have an ASP.NET MVC form that when submitted can return either an ActionResult if there was an error with the data, or if everything is fine it redirects to a different action that returns a FileRes

I have an ASP.NET MVC form that when submitted can return either an ActionResult if there was an error with the data, or if everything is fine it redirects to a different action that returns a FileResult.

I've created a bit of a sample to provide an idea of what I am doing. This is the html:

<%
using (Html.BeginForm())
%>
    <%= Html.ValidationSummary(
        "Edit was unsuccessful. Please correct the errors and try again.") %>
    <%= Html.TextBox("YourName", Model.YourName)%>
    <%= Html.ValidationMessage("YourName", "*") %>
    <input type="submit" />
<% } %>

and the controller code is:

[AcceptVerbs(Htt开发者_JS百科pVerbs.Post)]
public ActionResult MyPostSample(string YourName)
{
    if (string.IsNullOrEmpty(YourName))
    {
         ModelState.AddModelError("YourName", "You must specify a name");
    }

    if (ModelState.IsValid)
    {
         // get the file
         RedirectToAction("GetFile");
    }
    else
    {
         // return this actions View with errors
         return View();
    }
}

public FileResult GetFile(string YourName)
{
    // return file here
}

The reason for the ActionResult is to populate ModelState errors so the user can correct and try again.

This all works fine, except I would like the form to be reset or cleared if a file is returned by the server. Currently the user gets a File dialog, but the form retains the submitted values. What can I do to reset the form after a successful submit?


I would recommend returning a new form with a bit of javascript that triggers the download (along with a link to use if the download doesn't start). I feel that this is the best way to make sure that it works both with and without javascript and gets you the sort of behavior that you desire.


Further to what @tv has said you might consider having a composit model. That is, a model that has two models. The first would take your form details and the second the file details.

When you return from a success, you could return an empty form model and a filled file model.

Then, and I might be wtrong here, but the UI should really take care of itself.

0

精彩评论

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