1

我有一個模型(簡化,除去多餘的屬性):HttpPostedFileBase沒有被填充的

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屬性爲null。 ModelState是無效的,說「格式化數據文件字段是必需的。」這個相同的代碼在我所做的一些MVC-3項目中工作得很好 - 在MVC-4中對此有什麼不同?

回答