Mr Coder
Mr Coder

Reputation: 847

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

            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 is have value but model is null .

how can i solve this problem ?

Upvotes: 0

Views: 138

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239290

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.

EDIT

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.

Upvotes: 1

Related Questions