1

I'm building an essay contest page. The essay can be written into a textarea or can be uploaded. I'm new to asp.net mvc and have followed along with Sanderson's Pro ASP.NET MVC Framework.

I'm having trouble with maintaining the posted file on the round-trip from failing field validation.

Reading this I named my input file as the same as the model field name and am passing this as an input into the controller action:

[AcceptVerbs(HttpVerbs.Post)]
public ViewResult SubmitEssay(Essay essay, bool acceptsTerms,
    HttpPostedFileBase essay_filepath,
    HttpPostedFileBase budget_filepath)
{
    if (!acceptsTerms)
        ModelState.AddModelError("acceptsTerms", 
                                 "You must accept the terms and conditions.");
    else
    {
        try
        {
            // stuff uploaded file values
            if (string.IsNullOrEmpty(essay.essay_filepath) 
                   && (essay_filepath!= null))
            {
                essay.essay_filepath = essay_filepath.FileName;
            }

            if (string.IsNullOrEmpty(essay.budget_filepath) 
                   && (budget_filepath != null))
            {
                essay.budget_filepath = budget_filepath.FileName;
            }

This is working, per se, but when I go to validate the other fields, upon round-trip the file upload field no longer contains the upload path, such that when I re-submit, after filling in the required fields, there is no posted file.

What is the best way to maintain a posted file through a round-trip? Can you even set the "value" of a <input type="file" /> field? Should I use two fields (one hidden) and set the file input field using jQuery?

What have others done?

Thanks.

Community
  • 1
  • 1
Scott
  • 1,862
  • 1
  • 33
  • 53
  • http://www.cs.tut.fi/~jkorpela/forms/file.html#value%29 – Gregoire Jan 26 '10 at 21:33
  • Yeah, I'm thinking I should just add a comment stating that there were errors, so the input file will need to be chosen again. – Scott Jan 26 '10 at 21:38
  • 1
    And maybe add some client side JS validators to prevent submitting unless all required fields are filled in.. – mare Jan 27 '10 at 00:15
  • Yep, I was actually going to do this after I set up the business layer protections. I read last night about how the next version of asp.net mvc will allow for business layer and javascript validation with the same lines of code. (perhaps this is also possible now, but I just don't know enough about it.) – Scott Jan 27 '10 at 14:28

1 Answers1

0

The answer is, as you can see in the comments, that I shouldn't even try to do this. Instead, I'm going to add a ValidationMessage saying that because there were errors, the file will have to be chosen again.

Scott
  • 1,862
  • 1
  • 33
  • 53