2
我有一個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>
}
用戶可以選擇點擊「添加附件」鏈接,不需要附件添加多個附件。
我的模型如下:
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。我如何導致驗證忽略上傳的文件?
這就是它!謝謝! – 2012-01-31 17:59:37