文件上载导致模型验证失败

时间:2012-01-31 17:41:46

标签: c# asp.net-mvc-3 validation file-upload

我有一个MVC3表单绑定到具有文件上载控件的模型。 (为简洁起见,删除了额外的HTML):

@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>
}

用户可以通过点击&#34;添加附件&#34;来选择添加多个附件。链接,不需要附件。

我的模型如下:

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

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

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

(注意:我还尝试将附件移出模型,进入我的动作方法的参数,结果相同)

我的行动:

[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
    }
}

当没有选择上传文件时,此表单正常工作并且验证通过。当我选择要上传的文件时,ModelState.IsValid会变为false。如何使验证忽略上传的文件?

1 个答案:

答案 0 :(得分:2)

您需要确保您的表单使用了正确的“enctype”。

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

MVC 3 file upload and model binding