2014-04-10 45 views
0

我有一個帶有3個輸入(文本,圖像,提交按鈕)的表單。MVC上傳並保存帶有Ajax的表單圖像

@using (Html.BeginForm("Save", "User", FormMethod.Post, new {Id="Form1", enctype = "multipart/form-data"})) 
     { 
     <input id="FileUploadInput" name="Image" type="file"/> 
     <input id="FirstName" Name="FirstName"> 
     <input type="submit" id="inputSubmit" value="Save" /> 
     } 

現在我想從JavaScript和AJAX

$("#inputSubmit").click(function (e) { 
      e.preventDefault(); 
      var form = $("#Form1"); 
      form.validate(); 
      if (form.valid()) { 
       $.ajax({ 
        url: "/User/Save", 
        data: form.serialize(), 
        type: "POST", 
        success: function (data) { 
         if (data === "") { 
          location.reload(); 
         } 
         else { 
          $(".content").html(data); 
          $.validator.unobtrusive.parse($(".content")); 
         } 
        } 
       }); 
      } 

      return false; 
     }); 

提交此表在我的控制文件,我有。

public ActionResult Save(UserProfileSettings settings) 
{ 
    var image = setings.Image 
    var name = settings.Firstname 
} 

我的模型

public class UserProfileSettings 
{ 
    public string FirstName { get; set; } 
    public HttpPostedFileBase Image { get; set; } 
} 

的問題是,在我的控制器方法我得到settins.FirstName,但settings.Image始終爲空。我認爲,用這種方法不可能序列化圖像文件。

+0

你或許可以從下面的例子中受益這裏顯示控制器:http://powerdotnetcore.com/ ASP淨MVC/ASP淨MVC-簡單的Ajax文件上傳,using- jquery –

回答

0

由於達林季米特洛夫suggested之前,最好使用jquery forms plugin。我已經發布了這個在我的另一個答案here

簡單的例子

查看

@using (Ajax.BeginForm("YourAction", "YourController", new AjaxOptions() { HttpMethod = "POST" }, new { enctype = "multipart/form-data"})) 
{ 
    @Html.AntiForgeryToken() 
    <input type="file" name="files"><br> 
    <input type="submit" value="Upload File to Server"> 
} 

[HttpPost] 
[ValidateAntiForgeryToken] 
public void YourAction(IEnumerable<HttpPostedFileBase> files) 
{ 
    if (files != null) 
    { 
     foreach (var file in files) 
     { 
      // Verify that the user selected a file 
      if (file != null && file.ContentLength > 0) 
      { 
       // extract only the fielname 
       var fileName = Path.GetFileName(file.FileName); 
       // TODO: need to define destination 
       var path = Path.Combine(Server.MapPath("~/Upload"), fileName); 
       file.SaveAs(path); 
      } 
     } 
    } 
} 
+0

但我想提交表單從javascript方法 $(「#inputSubmit」)。click(function(e){ –

+1

@ArmenMkrtchyan:Ajax.BeginForm()是一種jQuery的ajax表單提交,這很容易做這個。 http://stackoverflow.com/questions/5410055/using-ajax-beginform-with-asp-net-mvc-3-razor –

+0

下來選民應該看到達林季米特洛夫的建議。 http://stackoverflow.com/questions/2780241/asp-net-mvc-file-upload-ajax-post?lq=1 –