我需要上傳圖片在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);
}
HttpPostedFileBase pic
是具有價值,但型號爲NULL。
我該如何解決這個問題?
在窗體名稱是pic,但un控制器名稱是userphoto,謝謝 – Kianoush
編號在控制器中,名稱也是'pic',因爲您將它作爲參數。無論如何,表單和動作參數/模型屬性名稱必須匹配。如果你想讓這個值進入'UserPhoto',那麼你的表單中的輸入也必須命名爲'UserPhoto'。 –