Kyle Trauberman
Kyle Trauberman

Reputation: 25684

File Upload Causes Model Validation to Fail

I have an MVC3 form bound to a model with a file upload control. (Extra HTML removed for brevity):

@model Models.MessageModel

<script type="text/javascript">
    var numAttachments = 0;
    $(function () {
        $(".add-attachment").click(function () {
            $(".attachments").append("<div><input type=\"file\" name=\"attachments\" id=\"attachment" + numAttachments + "\" /></div>");
        });
    });
</script>

@using (Html.BeginForm())
{
    @Html.ValidationSummary()
        <div class="field-label">Subject:
            @Html.EditorFor(model => model.Subject)
        </div>
        <div class="attachments">
        </div>
        <div>
            <a href="javascript:void(0);" class="add-attachment">Add Attachment</a>
        </div>
        <div class="message-text">@Html.TextAreaFor(model => model.Text, new { cols = 107, rows = 10 })</div>
        <input type="submit" value="Send Message" />
    </div>
}

Users can choose to add multiple attachments by clicking the "add attachment" link, attachments are not required.

My model is as follows:

public class MessageModel
{
    [Required]
    public string Subject { get; set; }

    [Required]
    public string Text { get; set; }

    public IEnumerable<HttpPostedFileBase> Attachments { get; set; }
}

(NOTE: I've also tried moving the attachments out of the model, into an argument to my action method with the same results)

My Action:

[HttpPost]
public ActionResult New(MessageModel message)
{
    // this check passes if no file is uploaded
    // but once a file is uploaded, this evaluates to false
    // even if the model is valid
    if (ModelState.IsValid) 
    {
        // do stuff
    }
}

This form works fine and validation passes when no file is selected for upload. When I choose a file for upload, ModelState.IsValid becomes false. How can I cause validation to ignore uploaded files?

Upvotes: 2

Views: 1696

Answers (1)

Zach Green
Zach Green

Reputation: 3460

You need to make sure your form is using the correct "enctype".

@using (Html.BeginForm("New", "Controller", FormMethod.Post, new { enctype = "multipart/form-data" }))

MVC 3 file upload and model binding

Upvotes: 2

Related Questions