views:

180

answers:

2

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?

+1  A: 

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.

tvanfosson
Good idea - I didn't really think about a two-step process, I was focused on attempting to do everything in one step.
eyesnz
I've made the change to the code: if everything is valid from the original View, a new View is called. And in this new View, it does as you suggested and autoloads the file via the File's action. Seems to work great! Thanks!
eyesnz
A: 

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.

griegs