Kianoush Kianoush - 1 year ago 103
ASP.NET (C#) Question

not Fill model When i Use HttpPostedFileBase

i need to upload pic in asp mvc 5 .

but when i select image show me in

The UserPhoto field is required.

this my Code :

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};

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

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

enter image description here

enter image description here

HttpPostedFileBase pic
is have value but model is null .

how can i solve this problem ?

Answer Source

Well, first, it seems you mean model.UserPhoto is null, since model very clearly does have a value, as do most of its properties, except UserPhoto.

The question, then, is are you posting something with the name UserPhoto in your form? If not, then of course it's null. The only things that will be set after post are properties that were actually posted. Anything else will be either null or the default value of the type, if it's non-nullable (i.e. 0 for int).

However, you shouldn't need it. First, this appears to be a "create" view, so UserPhoto will have no value to begin with. If pic is set, you will set UserPhoto to that, otherwise, nothing was uploaded, and UserPhoto should be null. If this were an "edit" view, though, you would merely pull a copy of the user from the database first (which will include the current UserPhoto). You would only change it, again, if pic were posted.


The error is because you have UserPhoto set as required. Just remove that validation. Or, you can simply get rid of pic and post directly to UserPhoto.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download