Home > Enterprise >  How to Edit Image in Existing Member
How to Edit Image in Existing Member

Time:06-01

I Use bootstrap cards and i want picture can also edit on existing user or i Edit picture of any member

This is my Controller

This is my edit Functionality where i can edit My Member so i want i update all existing user picture

public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var member = await _context.Member.FindAsync(id);
            if (member == null)
            {
                return NotFound();
            }
            return View(member);
        }

        // POST: HomePage/Edit/5
        // To protect from overposting attacks, enable the specific properties you want to bind to.
        // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, [Bind("MemberId,Name,Gender,DOB,MaritalStatus,Address,PhoneNo,Skills,Hobbies,JobTitle,Technology")] Member member)
        {
            if (id != member.MemberId)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(member);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!MemberExists(member.MemberId))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            return View(member);
        }

This is a View of my project this is same as create class

<div >
        <div >
            <label >MemberImage</label>
            <div >
                <div id="chooseFile">
                    <input  type="file" name="photo" accept="image/*" />
                </div>
            </div>
        </div>
    </div>

when i edit the one existing member enter image description here

2.i add image enter image description here

and save it will save the img but now they cannot save image

Exception Occurs when i open edit enter image description here

*Edit Page Code

 <div >
        <div >
            <label >MemberPicture</label>
            <div >
                <img src="~/ImageName/Cover/@Model.Member.ImageName"
                     
                     height="50" width="75"
                     style="border:1px"
                     asp-append-version="true" accept="image/*" />
                <span><a href="@Model.Member.ImageName">@Model.Member.ImageName</a></span>
                <div id="chooseFile">
                    <input  type="file" name="photo" accept="image/*" />
                </div>
            </div>
        </div>
    </div>

View Model

using System;
using TeamManagement.Models;

namespace TeamManagement.ViewModel
{
    public class MemberViewModel
    {
        public Member Member { get; set; }
        public IFormFile? Photo { get; set; }
    }
}

CodePudding user response:

"This is my edit Functionality where I can edit My Member so i want i update all existing user picture?"

If you look into the Member List, it usually contains rows of users along with Id. So we have to find the particular Id and then need to retrieve the value of that Id finally we will update the existing value with the new value. As seen on the screenshot below:enter
image description here

Algorithm

    ============
    Algorithm
    ============
    1.From The Member List Click On Perticular Member Id
    2.Find The Member Information By that Id
    3.Load The Edit Page With That Id Same As Create Member Page
    4.After Required Chnage Submit the Edit Page Which Containing the Member Mdoel Data With A ID
    5.Save the Image Into Folder First Same As Create
    6.Search The Member Object By Id
    7.Set New Value Into The Member Object You Have Founded In Step 6
    8.Save The Context And Redirect To Member List

Controller Action For Loading Edit Page

public async Task<IActionResult> EditMember(int memberId)
    {
        var memeber = await _context.Members.FindAsync(memberId); // Getting member by Id from database
        return View(new MemberViewModel() { Member = memeber });
       
    }

View Model

public class MemberViewModel
    {
        public Member Member { get; set; }
        public IFormFile? Photo { get; set; }
    }

View Edit

@model DotNet6MVCWebApp.Models.MemberViewModel
<div>
    <form asp-action="EditMember" method="post" enctype="multipart/form-data">
        <div asp-validation-summary="ModelOnly"></div><input type="hidden" asp-for="Member.MemberId" />
        <div>
            <h4><strong>Member Details</strong> </h4>

            <table >

                <tr>
                    <th> <label asp-for="Member.Name"></label></th>
                    <td> <input asp-for="Member.Name"  placeholder="Enter member name" /><span asp-validation-for="Member.Name"></span></td>
                </tr>
                <tr>
                    <th> <label asp-for="Member.Gender"></label></th>
               
                    <td>
                        <select asp-for="Member.Gender" >
                            <option value="Male">Male</option>
                            <option value="Female">Female</option>
                        </select>
                    <span asp-validation-for="Member.Gender"></span>
                
                </td>
                </tr>
                <tr>
                    <th> <label asp-for="Member.DOB"></label></th>
                    <td> <input asp-for="Member.DOB"  placeholder="Enter animal category" /><span asp-validation-for="Member.DOB"></span></td>
                </tr>
                <tr>
                    <th> <label asp-for="Photo"></label></th>
                 
                    <td>
                        <img src="~/ImageName/Cover/@Model.Member.ImageName"
                             
                             height="50" width="75"
                             style="border:1px"
                             asp-append-version="true" accept="image/*" />
                        <span><a href="@Model.Member.ImageName">@Model.Member.ImageName</a></span>
                        <div id="chooseFile"><input type="file" name="photo"  accept="image/*" /></div>

                    </td>
                </tr>
                <tr>
                    <th>  <button type="submit"  style="width:107px">Update</button></th>
                    <td> </td>
                </tr>
                <tr>
                    <th>@Html.ActionLink("Back To List", "MemberList", new { /* id=item.PrimaryKey */ }, new { @class = "btn btn-success" })</th>
                    <td> </td>
                </tr>
            </table>
        </div>
    </form>

</div>

Note: Here make sure your src="~/ImageName/Cover/@Model.Member.ImageName" is correct as per your picture location. Otherwise picture will not be displayed

Controller When Submit Edit

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> EditMember(MemberViewModel model, IFormFile photo)
    {
        if (photo == null || photo.Length == 0)
        {
            return Content("File not selected");
        }
        //Save The Picture In folder
        var path = Path.Combine(_environment.WebRootPath, "ImageName/Cover", photo.FileName);
        using (FileStream stream = new FileStream(path, FileMode.Create))
        {
            await photo.CopyToAsync(stream);
            stream.Close();
        }

        //Bind Picture info to model
        model.Member.ImageName = photo.FileName;

        //Finding the member by its Id which we would update
        var objMember = _context.Members.Where(mId => mId.MemberId == model.Member.MemberId).FirstOrDefault();

        if (objMember != null)
        {
            //Update the existing member with new value
            objMember!.Name = model.Member.Name;
            objMember!.Gender = model.Member.Gender;
            objMember!.DOB = model.Member.DOB;
            objMember!.ImageName = model.Member.ImageName;
            objMember!.ImageLocation = path;

            await _context.SaveChangesAsync();
        }
        return RedirectToAction("MemberList");


    }

Note: Here we will update the _context.SaveChangesAsync() instead of adding new data. This is the key point for edit. Update the information which we have got by ID

Output

enter image description here

Hope it would guide you accordingly, what you are trying to implement.

  • Related