HttpPostedFileBase未填充

时间:2012-11-13 19:41:05

标签: asp.net-mvc file-upload razor asp.net-mvc-4 visual-studio-2012

我有一个模型(简化,删除了无关的属性):

public class SubmitModel
{
    [Required]
    [DataType("FileUpload")]
    [Display(Name = "Formatted Data File")]
    public HttpPostedFileBase FormattedDataFile { get; set; }
}

控制器:

[HttpPost]
public ActionResult Submit(SubmitModel model)
{
    if (this.ModelState.IsValid)
    {
        //...
    }

    return this.View(model);
}

FileUpload视图:

@{
    IDictionary<string, object> htmlAttributes = Html.GetUnobtrusiveValidationAttributes(string.Empty);
}

<input type="file" id="@this.ViewData.TemplateInfo.GetFullHtmlFieldId(string.Empty)" name="@this.ViewData.TemplateInfo.GetFullHtmlFieldName(string.Empty)" @(new MvcHtmlString(htmlAttributes.ToHtmlAttributesString())) />
@Html.ValidationMessage(string.Empty)

一个简单的观点:

@model SubmitModel

@using (Html.BeginForm())
{
    <div class="Form">
        @Html.EditorForModel()

        <div class="Footer">
            <button class="Button" data-options='{ "icons": { "primary": "ui-icon-disk" } }'>Submit</button>
        </div>
    </div>
}

呈现给这个HTML:

<form action="/Data/Submit" method="post">
    <div class="Form">
        <div class="Item">
            <div class="Label Required">Formatted Data File:</div>
            <div class="Input">
                <input type="file" id="FormattedDataFile" name="FormattedDataFile"  data-val-required="The Formatted Data File field is required." data-val="true" />
                <span class="field-validation-error" data-valmsg-for="FormattedDataFile" data-valmsg-replace="true">The value &#39;Test.xlsx&#39; is invalid.</span>
            </div>
        </div>

        <div class="Footer">
            <button class="Button" data-options='{ "icons": { "primary": "ui-icon-disk" } }'>Submit</button>
        </div>
    </div>
</form>

点击Submit后,我被带到正确的控制器/操作,我的模型的FormattedDataFile属性为空。 ModelState无效,表示“格式化数据文件字段是必需的”。这个相同的代码在我做过的一些MVC-3项目中运行良好 - 在MVC-4中有什么不同吗?

1 个答案:

答案 0 :(得分:1)

我认为你在

形式中缺少enctype="multipart/form-data"

http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2