Question

How do you add the option to upload a profile image to the default RegisterModel in MVC 4?

Was it helpful?

Solution

This answer converts the image to a byte array so that you can then save it in a database. It can easily be modified if you wanted to save the image to file store.

The code for the View Model. The important part is the multipart/form-data attribute:

 @using (Html.BeginForm("Register", "Account", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        @Html.AntiForgeryToken()
        @Html.ValidationSummary()

        <fieldset>
            <legend>Registration Form</legend>
            <ol>
                <li>
                    @Html.LabelFor(m => m.UserName)
                    @Html.TextBoxFor(m => m.UserName)
                </li>
                <li>
                    @Html.LabelFor(m => m.Password)
                    @Html.PasswordFor(m => m.Password)
                </li>
                <li>
                    @Html.LabelFor(m => m.ConfirmPassword)
                    @Html.PasswordFor(m => m.ConfirmPassword)
                </li>
                <li>
                    <label for="register-avatar">Upload your photo</label>
                    <input id="register-avatar"  type="file" name="ProfileImage" />
                </li>
            </ol>
            <input type="submit" value="Register" />
        </fieldset>
    }

The RegisterModel:

public class RegisterModel
{
    [Required]
    [Display(Name = "User name")]
    public string UserName { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [DataType(DataType.Password)]
    [Display(Name = "Confirm password")]
    [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
    public string ConfirmPassword { get; set; }

    public HttpPostedFileBase ProfileImage { get; set; }

}

The AccountController's HTTPPost for the Register.cshtml View:

[HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Register(RegisterModel model)
    {

        if (ModelState.IsValid)
        {
            // Attempt to register the user
            try
            {
                WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
                WebSecurity.Login(model.UserName, model.Password);

                MemoryStream target = new MemoryStream();
                model.ProfileImage.InputStream.CopyTo(target);
                byte[] data = target.ToArray();

                var profileImage = new ProfileImage();
                profileImage.Data = data;
                profileImage.MimeType = model.ProfileImage.ContentType;

                /// other code to save the image to the database

                return RedirectToAction("Index", "Profile/" + model.UserName);
            }
            catch (MembershipCreateUserException e)
            {
                ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
            }
        }

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

This is a quick run down of how I managed to upload a profile image along with the registration built into the MVC 4 template.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top