开发者

ASP.NET MVC - File Uploading and Model Binding

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(Htt开发者_JS百科pVerbs.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.


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜