2016-10-03 58 views
0

我需要上傳圖片在asp mvc 5。不填充模型當我使用HttpPostedFileBase

但是,當我選擇圖像顯示我在The UserPhoto field is required.

這是我的代碼:

public async Task<ActionResult> Register(RegisterViewModel model, HttpPostedFileBase pic) 
    { 
     if (ModelState.IsValid) 
     { 
      if (pic != null) 
      { 
       pic = Request.Files[0]; 
       var ext = System.IO.Path.GetExtension(pic.FileName); 
       if (ext == ".jpg" || ext == ".png" || ext == ".jpeg") 
       { 
        string filename = model.Name + model.PhoneNumber + ext; 
        pic.SaveAs(@"~/Image/" + filename); 
        model.UserPhoto = filename; 
       } 
      } 
      var user = new ApplicationUser { Name = model.Name, Family = model.Family, PhoneNumber = model.PhoneNumber, UserName = model.Email, Email = model.Email}; 

      user.UserPhoto=model.UserPhoto; 
      var result = await UserManager.CreateAsync(user, model.Password); 
      if (result.Succeeded) 
      { 
       await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); 
       return RedirectToAction("Index", "Home"); 
      } 
      AddErrors(result); 
     } 

     // If we got this far, something failed, redisplay form 
     return View(model); 
    } 

enter image description here

enter image description here

HttpPostedFileBase pic是具有價值,但型號爲NULL。

我該如何解決這個問題?

回答

1

嗯,首先,看起來你的意思是model.UserPhoto爲空,因爲model非常清晰,它的大部分屬性都是如此,除了UserPhoto

問題是,你是在你的表單中發佈名稱爲UserPhoto的東西嗎?如果不是,那麼當然它是空的。 post後設置的唯一東西是實際發佈的屬性。如果不可爲空(即0int),則其他任何值都將爲null或該類型的默認值。

但是,你不應該需要它。首先,這似乎是一個「創造」的觀點,所以UserPhoto將沒有價值開始。如果pic已設置,則您將設置爲UserPhoto,否則不會上傳任何內容,並且UserPhoto應該爲空。不過,如果這是一個「編輯」視圖,那麼您只需首先從數據庫中提取用戶的副本(其中將包含當前的UserPhoto)。如果發佈pic,則只會再次更改它。

編輯

的錯誤是因爲你有UserPhoto根據需要設置。只要刪除該驗證。或者,您可以簡單地擺脫pic並直接發佈到UserPhoto

+0

在窗體名稱是pic,但un控制器名稱是userphoto,謝謝 – Kianoush

+0

編號在控制器中,名稱也是'pic',因爲您將它作爲參數。無論如何,表單和動作參數/模型屬性名稱必須匹配。如果你想讓這個值進入'UserPhoto',那麼你的表單中的輸入也必須命名爲'UserPhoto'。 –