2012-01-29 20 views
1

這裏是一個控制器操作方法,我要上傳用戶的個人資料圖片...MVC 3的UpdateModel和調用SaveChanges

[HttpPost] 
    public ActionResult UploadPhoto(int id, FormCollection form) 
    { 
     Profile profile = db.Profiles.Find(id); 

     var file = Request.Files[0]; 

     if (file.ContentLength > 512000) 
     { 
      ModelState.AddModelError(string.Empty, "Please limit your photo to 500 KB"); 
     } 

     bool IsJpeg = file.ContentType == "image/jpeg"; 
     bool IsPng = file.ContentType == "image/png"; 
     bool IsGif = file.ContentType == "image/gif"; 

     if (!IsJpeg && !IsPng && !IsGif) 
     { 
      ModelState.AddModelError(string.Empty, "Only .jpeg, .gif, and .png images allowed"); 
     } 

     if (file == null || file.ContentLength <= 0) 
     { 
      ModelState.AddModelError(string.Empty, "You must select an image to upload"); 
     } 

     if (ModelState.IsValid) 
     { 
      try 
      { 
       string newFile = Path.GetFileName(file.FileName); 
       file.SaveAs(Server.MapPath("/Content/users/" + User.Identity.Name + "/" + newFile)); 
       profile.ProfilePhotoPath = "/Content/users/" + User.Identity.Name + "/" + newFile; 
       UpdateModel(profile); 
       db.SaveChanges(); 
       return RedirectToAction("Index"); 
      } 
      catch 
      { 
       return View(); 
      } 
     } 
     return View(); 
    } 

當我嘗試上傳的圖像,並通過它一步......

當應用程序碰到這條線:

profile.ProfilePhotoPath = "/Content/users/" + User.Identity.Name + "/" + newFile; 

它顯示了ProfilePhotoPath值爲 「System.Web.HttpPostedFileWrapper」

現在,當應用程序打下一行:

UpdateModel(profile); 

它顯示了ProfilePhotoPath值爲「/Content/users/WebWired/myprofilepic.png」,因爲它應該...

但隨後,當應用程序打下一行:

db.SaveChanges(); 

突然之間ProfilePhotoPath值是「System.Web.HttpPostedFileWrapper」了......這是它是如何保存的?

如果不是奇怪的是,它的工作之前,我開始添加邏輯文件上傳,但真的不應該有什麼關係,因爲它經過了這一切起來......

不任何人都明白這裏發生了什麼,爲什麼這樣做,我做錯了什麼?

回答

1

UpdateModel()使用來自控制器值提供程序的值(即POST參數等)更新您的配置文件對象。如果它找到名爲「ProfilePhotoPath」的POST參數,則您的profile.ProfilePhotoPath屬性將設置爲該值,覆蓋您剛剛手動設置的值。

您的<input type="file">字段(或用於將文件發佈到服務器的任何方法)似乎具有名稱屬性:「ProfilePhotoPath」。該字段將變成服務器上的HttpPostedFileWrapper對象,包含關於所張貼的文件(內容長度,類型,文件名等)的信息。而且它是對象的UpdateModel將分配給您的profile.ProfilePhotoPath財產(因爲它具有相同的名稱屬性)。因爲它分配一個對象的字符串屬性,它會強制對象轉換成字符串,從而產生「System.Web.HttpPostedFileWrapper」。

+0

「看來‘ProfilePhotoPath’是你上傳文件的格式名稱。」你是對的,這是...哇,謝謝你,一個完整的DUH!我的時刻......再次完美地工作。 – 2012-01-29 18:57:34

+0

我剛編輯擺脫了很多關於張口閉口我是如何得到這個結論的(完全忘記了控制器::的UpdateModel是MVC提供的方法 - 我從來沒有使用它)。那是*我* DUH!時刻。 :-) – JimmiTh 2012-01-29 19:04:25