2015-11-16 106 views
0

我遇到了一些問題,我無法從ajaxOptions的形式獲取文件。下面是代碼..MVC HttpPostedFileBase始終爲空與ajax選項

@using (Ajax.BeginForm(null, null, new AjaxOptions { OnBegin = "blockUI", OnSuccess = "handleFormSuccess", OnFailure = "onAjaxFailure" }, new { enctype = "multipart/form-data" })) 
{ 
<div class="col-md-4"> 
          <div class="form-group"> 
           @Html.LabelFor(model => model.MediaName, new { @class = "control-label" }) 
           <span class="text-danger" aria-required="true"> * </span> 
           @Html.TextBoxFor(model => model.MediaName, new { @class = "form-control", @placeholder = LocalizationViewModel.Media.MediaName }) 
           <span class="text-danger">@Html.ValidationMessageFor(model => model.MediaName)</span> 
          </div> 
         </div> 
<div class="row col-md-12"> 
         <div id="imageContent" class="form-group"> 
          @Html.Label(@LocalizationViewModel.Media.Image, new { @class = "control-label" }) 
          <div class="col-md-12"> 
           @Html.TextBoxFor(model => model.MediaFile, new { type = "file" }) 
          </div> 
         </div> 
        </div> 
    } 

如果我改變這個,它的工作文件。

@using (Html.BeginForm("CreateMedia", "Media", FormMethod.Post, new { @class = "form-horizontal", enctype = "multipart/form-data" })) 
{ 
<div class="col-md-4"> 
          <div class="form-group"> 
           @Html.LabelFor(model => model.MediaName, new { @class = "control-label" }) 
           <span class="text-danger" aria-required="true"> * </span> 
           @Html.TextBoxFor(model => model.MediaName, new { @class = "form-control", @placeholder = LocalizationViewModel.Media.MediaName }) 
           <span class="text-danger">@Html.ValidationMessageFor(model => model.MediaName)</span> 
          </div> 
         </div> 
     <div id="imageContent" class="form-group"> 
          @Html.Label(@LocalizationViewModel.Media.Image, new { @class = "control-label" }) 
          <div class="col-md-12"> 
           @Html.TextBoxFor(model => model.MediaFile, new { type = "file" }) 
          </div> 
         </div> 
        </div> 
} 

下面是我的控制器和視圖模型。

[HttpPost] 
     [ValidateAntiForgeryToken] 
     public async Task<ActionResult> CreateMedia(CreateMediaViewModel viewModel) 
     { // some code here 
} 


public class CreateMediaViewModel 
    { 
[Display(ResourceType = typeof(Media), Name = "MediaName")] 
     [Required(ErrorMessageResourceType = typeof(Message), ErrorMessageResourceName = "MessageFieldRequired")] 
     public string MediaName { get; set; } 

     [Display(ResourceType = typeof(Media), Name = "Image")] 
     public HttpPostedFileBase MediaFile { get; set; } 
    } 

有沒有人有想法讓它工作? :(我被困在這裏了一段時間...感謝..

+2

您需要使用'FormData'我希望使用AJAX來發布文件,請參閱[這個答案](http://stackoverflow.com/questions/29293637。 /如何對append-整套模型到表單數據並獲取mvc/29293681#29293681) –

+0

我已經使用了新的MVC 5項目的樣本......並且它運行良好。你確定你粘貼了一切嗎?或者,也許這個問題僅在MVC 3/4項目中? – Kryszal

回答