2014-01-20 14 views
0

我想通過使用MVC 4 ajax表單添加圖像,但它總是返回空值。我添加了我的模型,控制器和視圖。MVC 4 ajax表單圖像上傳失敗

我查看

@using (Ajax.BeginForm("Create", "Images", new AjaxOptions { HttpMethod = "Post", OnSuccess = "OnSuccess", OnFailure = "OnFailure", UpdateTargetId = "messageDiv" }, new { enctype = "multipart/form-data" })) 
    { 
     @Html.AntiForgeryToken() 
     @Html.ValidationSummary(true) 
     <div class="editor-field"> 
        @Html.LabelFor(model => model.Image.Description, new { @class = "control-label" }) 
        <div class="controls"> 
         @Html.TextBoxFor(model => model.Image.Description) 
        </div> 
        @Html.TextBoxFor(model => model.FileImage, new { type = "file" }) 
        @Html.ValidationMessageFor(model => model.FileImage) 
       </div>... 
    } 

我的模型

public class ImageViewModel 
    { 

     public IList<Image> Images { get; set; } 
     public Image Image { get; set; } 
     public HttpPostedFileBase FileImage { get; set; } 

    } 

我的控制器

[HttpPost] 
     [ValidateAntiForgeryToken] 
     public ActionResult Create(ImageViewModel model, HttpPostedFileBase FileImage) 
     { 
      if (ModelState.IsValid) 
      { 
       var x = FileImage.FileName; 
       var imageUrl = Path.GetFileName(model.FileImage.FileName); 
       ... 
      } 
     } 

在這個例子中,我無法獲得FileName。它總是返回空值。你能幫我解決這個問題嗎?我會很高興的。

+0

使用Ajax.BeginForm你不能上傳文件。請參閱http://stackoverflow.com/questions/8499748/mvc3-file-upload-using-ajax-form-request-files-empty – Dave

+0

非常感謝。 – koirene

回答

0

我寧願使用試圖綁定,爲模型的要求這一翻譯讀取圖像,

public ActionResult Create(ImageViewModel model) 
{ 
    if (Request.Files != null) 
    { 
     HttpPostedFileBase file = Request.Files[0]; //assuming that's going to be the first file 
     if (file.ContentLength > 0) 
     { 
      string fileName = Path.GetFileName(file.FileName); 
      string directory = Server.MapPath("/"); //change ths to your actual upload folder 
      file.SaveAs(Path.Combine(directory, fileName)); 
     } 
    } 

} 
+0

您可以刪除方法中的FileImage參數。 –

+0

@ Djavier89更新!感謝您的觀察,只是複製並從koirene代碼粘貼它,我忘了更新簽名! –

+0

更改代碼運行良好後,我將我的Ajax.BeginForm轉換爲Html.BeginForm。非常感謝你。 – koirene