1

I want to display a profile picture from the uploaded Image but will have a default image if the user has not uploaded an image. I have this code which saves Image data to my database:

public class UserProfileModel : PageModel
    {
        private readonly UserManager<ApplicationUser> _userManager;
        public readonly IWebHostEnvironment _env;
        private readonly IPhoto _photo;

        public UserProfileModel(UserManager<ApplicationUser> userManager,
                                IWebHostEnvironment env)
        {
            _userManager = userManager;
            _env = env;
        }
        [BindProperty]
        [Required]
        [MaxLength(30, ErrorMessage = "USERNAME CANNOT EXCEED 30 LETTERS.")]
        public string Name { get; set; }
        [BindProperty]
        [Required]
        [DataType(DataType.Date)]
        public string DateOfBirth { get; set; }
        [BindProperty]
        [Required]
        [EmailAddress]
        [Display(Name = "Email Address")]
        public string Email { get; set; }
        [BindProperty]
        [Required]
        [DataType(DataType.PhoneNumber)]
        public string Mobile { get; set; }
        [BindProperty]
        [Required]
        public int Gender { get; set; }
        [BindProperty]
        [Required]
        public string Country { get; set; }
        [BindProperty]
        public IFormFile Image { get; set; }
        public List<SelectListItem> Countrydropdownlist { get; set; }
        public void OnGet()
        {
            Countrydropdownlist = GetCountryItems();
        }
        public List<SelectListItem> GetCountryItems()
        {
            string filepath = Path.Combine(_env.ContentRootPath, "CountryList.json");
            string jsonlist = System.IO.File.ReadAllText(filepath);
            var result = JsonConvert.DeserializeObject<RootCountry>(jsonlist);
            List<SelectListItem> _countrydropdownlist = new List<SelectListItem>();
            foreach (var nation in result.Countries)
            {
                _countrydropdownlist.Add(new SelectListItem { Value = nation.Code.ToString(), Text = nation.Name });
            }
            return _countrydropdownlist;
        }
        public async Task<IActionResult> OnPostUpdate()
        {
            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByNameAsync(User.Identity.Name);
                user.Name = Name;
                user.DateOfBirth = DateOfBirth;
                user.PhoneNumber = Mobile;
                user.Email = Email;
                user.Country = Country;
                user.Gender = Gender;
                if(Image != null)
                {
                    if(Image.Length > 0)
                    {
                        using var streamReader = Image.OpenReadStream();
                        using var memoryStream = new MemoryStream();
                        streamReader.CopyTo(memoryStream);
                        byte[] uploadedImage = memoryStream.ToArray();
                        user.ImageData = uploadedImage;
                    }
                }
                var result = await _userManager.UpdateAsync(user);
                if (result.Succeeded)
                {
                    //Repopulate dropdownlist
                    Countrydropdownlist = GetCountryItems();
                    return Page();
                }
            }
            return Page();
        }
    }

So I'm looking for something to add to the result.succeeded where an uploaded image replaces the default photo and is displayed as an image source in my Razor page. My cshtml:

@page
@model TravelMate.Pages.UserProfileModel
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, shrink-to-fit=no" />
    @{
        ViewBag.Title = "User Profile";
    }
    <style>
        img {
            border-radius: 50%;
        }
    </style>
    <link href="~/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
    <div class="container">
        <div class="row">
            <div class="col text-center">
                <br />
                   <img src="~/Image/GeneralUser.jpg" alt="User Image" style="height: 300px">
                <br />
            </div>
        </div>
        <form enctype="multipart/form-data" method="post" asp-page-handler="Update">
            <div asp-validation-summary="All" class="text-danger"></div>
            <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        <label asp-for="Name"></label>
                        <input asp-for="Name" class="form-control" />
                        <span asp-validation-for="Name" class="text-danger"></span>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <label asp-for="DateOfBirth"></label>
                        <input asp-for="DateOfBirth" class="form-control" />
                        <span asp-validation-for="DateOfBirth" class="text-danger"></span>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        <label asp-for="Mobile"></label>
                        <input asp-for="Mobile" class="form-control" />
                        <span asp-validation-for="Mobile" class="text-danger"></span>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <label asp-for="Email"></label>
                        <input asp-for="Email" class="form-control" />
                        <span asp-validation-for="Email" class="text-danger"></span>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-md-4">
                    <div class="form-group">
                        <label asp-for="Country"></label>
                        <select asp-for="Country" asp-items="@Model.Countrydropdownlist">
                            <option selected disabled> ---Select Country---</option>
                        </select>
                        <span asp-validation-for="Country" class="text-danger"></span>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-group">
                        <label asp-for="Gender"></label>
                        <select asp-for="Gender" class="form-control">
                            <option value="0" selected disabled>Select Gender</option>
                            <option value="1">Male</option>
                            <option value="2">Female</option>
                        </select>
                        <span asp-validation-for="Gender" class="text-danger"></span>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-group">
                        <label asp-for="Image"></label>
                        <div class="custom-file">
                            <input asp-for="Image" class="form-control custom-file-input" />
                            <label class="custom-file-label">Choose File...</label>
                        </div>
                    </div>
                </div>
            </div>
            @section Scripts{
                <script>
                    $(document).ready(function () {
                        $('.custom-file-input').on("change", function () {
                            var fileName = $(this).val().split("\\").pop();
                            $(this).next('.custom-file-label').html(fileName);
                        });
                    });
                </script>
            }
            <button type="submit" class="btn btn-primary">Update</button>
        </form>
    </div>
    <script src="~/jquery/jquery.slim.min.js"></script>
    <script src="~/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

Thank you.

Shanks Limbu
  • 117
  • 1
  • 12

2 Answers2

2

In the view:

@model User

@{
    if(Model.ImageData != null)
    {
        var base64 = Convert.ToBase64String(Model.ImageData);
        var userImage = String.Format("data:image/gif;base64,{0}", base64);
        <img src="@userImage" alt="User Image" style="height: 300px">
    }
    else
    {
      <img src="..." alt="User Image" style="height: 300px"> // Your default image is here
    }
    
}
TanvirArjel
  • 30,049
  • 14
  • 78
  • 114
0

You can try to save default image in the database, if the image is not uploaded

    public async Task<IActionResult> OnPostUpdate()
    {
        if (ModelState.IsValid)
        {
            var user = await _userManager.FindByNameAsync(User.Identity.Name);
            user.Name = Name;
            user.DateOfBirth = DateOfBirth;
            user.PhoneNumber = Mobile;
            user.Email = Email;
            user.Country = Country;
            user.Gender = Gender;
            if(Image != null)
            {
                if(Image.Length > 0)
                {
                    using var streamReader = Image.OpenReadStream();
                    using var memoryStream = new MemoryStream();
                    streamReader.CopyTo(memoryStream);
                    byte[] uploadedImage = memoryStream.ToArray();
                    user.ImageData = uploadedImage;
                }
            }
            //Here you will get the default image from server and save it
            else
            {
                string filepath = "default_image.PNG";
                byte[] uploadedImage = System.IO.File.ReadAllBytes(filepath);
                user.ImageData = uploadedImage;
            }
            var result = await _userManager.UpdateAsync(user);
            if (result.Succeeded)
            {
                //Repopulate dropdownlist
                Countrydropdownlist = GetCountryItems();
                return Page();
            }
        }
        return Page();
    }
Usman
  • 4,615
  • 2
  • 17
  • 33
  • Hy Usman, Thank you. I have default image in my wwwroot which is for all the uers. – Shanks Limbu Nov 19 '20 at 07:56
  • @ShanksLimbu you can check this https://stackoverflow.com/a/42599067/5671377 – Usman Nov 19 '20 at 08:05
  • Hi Usman, I don't know what I'm seeing there but I have this default image in wwwroot and I know how to retireve it. I just need a way to retrive data from database/uploaded image from user and use it as a new source for the user profile photo. – Shanks Limbu Nov 19 '20 at 09:50