Categories
asp.net-mvc forms html submit

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

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(HttpVerbs.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.