MVC CORE Edit Images

Kalyan A 285 Reputation points
2024-07-05T14:43:54.9833333+00:00

Database Contains images , when I try to edit the text , I need to upload images again , please suggest.

If there are no changes in images I don't want to upload them again.

Capturenotsaved.PNG

Capturedisplay.PNG

public partial class Questionsimg

{

public int Sno { get; set; }

public int No { get; set; }

public string? Topic { get; set; }

public string? QuestionTitle { get; set; }

public string? Opt1 { get; set; }

public string? Opt2 { get; set; }

public string? Opt3 { get; set; }

public string? Opt4 { get; set; }

public string? Answer { get; set; }

public int? Time { get; set; }

public int? Correct { get; set; }

public string? Solution { get; set; }

public byte[]? Imagedata { get; set; }

public byte[]? Imagesol { get; set; }
}

@model SupaCrud.Models.Questionsimg

@{

ruby
ViewData["Title"] = "Edit";
}

<h1>Edit</h1>

<h4>Questionsimg</h4>

<hr />

<div class="row">

xml
<div class="col-md-4">

    <form asp-action="Edit" enctype="multipart/form-data">

        <div asp-validation-summary="ModelOnly" class="text-danger"></div>

        <input type="hidden" asp-for="Sno" />

        <div class="form-group">

            <label asp-for="No" class="control-label"></label>

            <input asp-for="No" class="form-control" />

            <span asp-validation-for="No" class="text-danger"></span>

        </div>

        <div class="form-group">

            <label asp-for="Topic" class="control-label"></label>

            <input asp-for="Topic" class="form-control" />

            <span asp-validation-for="Topic" class="text-danger"></span>

        </div>

        <div class="form-group">

            <label asp-for="QuestionTitle" class="control-label"></label>

            <input asp-for="QuestionTitle" class="form-control" />

            <span asp-validation-for="QuestionTitle" class="text-danger"></span>

        </div>

        <div class="form-group">

            <label asp-for="Opt1" class="control-label"></label>

            <input asp-for="Opt1" class="form-control" />

            <span asp-validation-for="Opt1" class="text-danger"></span>

        </div>

        <div class="form-group">

            <label asp-for="Opt2" class="control-label"></label>

            <input asp-for="Opt2" class="form-control" />

            <span asp-validation-for="Opt2" class="text-danger"></span>

        </div>

        <div class="form-group">

            <label asp-for="Opt3" class="control-label"></label>

            <input asp-for="Opt3" class="form-control" />

            <span asp-validation-for="Opt3" class="text-danger"></span>

        </div>

        <div class="form-group">

            <label asp-for="Opt4" class="control-label"></label>

            <input asp-for="Opt4" class="form-control" />

            <span asp-validation-for="Opt4" class="text-danger"></span>

        </div>

        <div class="form-group">

            <label asp-for="Answer" class="control-label"></label>

            <input asp-for="Answer" class="form-control" />

            <span asp-validation-for="Answer" class="text-danger"></span>

        </div>

        <div class="form-group">

            <label asp-for="Time" class="control-label"></label>

            <input asp-for="Time" class="form-control" />

            <span asp-validation-for="Time" class="text-danger"></span>

        </div>

        <div class="form-group">

            <label asp-for="Correct" class="control-label"></label>

            <input asp-for="Correct" class="form-control" />

            <span asp-validation-for="Correct" class="text-danger"></span>

        </div>

        <div class="form-group">

            <label asp-for="Solution" class="control-label"></label>

            <input asp-for="Solution" class="form-control" />

            <span asp-validation-for="Solution" class="text-danger"></span>

        </div>

        <div class="form-group">

            <label asp-for="Imagedata" class="control-label"></label>

            <input name="imagedata" type="file" class="form-control" />

            <span asp-validation-for="Imagedata" class="text-danger"></span>

        </div>

        <div class="form-group">

            <label asp-for="Imagesol" class="control-label"></label>

            <input name="imagesol" type="file" class="form-control" />

            <span asp-validation-for="Imagesol" class="text-danger"></span>

        </div>

        <div class="form-group">

            <input type="submit" value="Save" class="btn btn-primary" />

        </div>

    </form>

</div>
</div>

<div>

sql
<a asp-action="Index">Back to List</a>
</div>

@section Scripts {

sql
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

  [HttpPost]

go
    [ValidateAntiForgeryToken]

    public async Task<IActionResult> Edit(int id, [Bind("Sno,No,Topic,QuestionTitle,Opt1,Opt2,Opt3,Opt4,Answer,Time,Correct,Solution,Imagedata,Imagesol")] Questionsimg questionsimg, IFormFile imagedata, IFormFile imagesol)

    {

        if (id != questionsimg.Sno)

        {

            return NotFound();

        }

        if (imagedata != null)

        {

            if (imagedata.Length > 0)

            {

                using (var target = new MemoryStream())

                {

                    imagedata.CopyTo(target);

                    questionsimg.Imagedata = target.ToArray();

                }

            }

        }

        if (imagesol != null)

        {

            if (imagesol.Length > 0)

            {

                using (var target = new MemoryStream())

                {

                    imagesol.CopyTo(target);

                    questionsimg.Imagesol = target.ToArray();

                }

            }

        }

        if (ModelState.IsValid)

        {

            try

            {

                _context.Update(questionsimg);

                await _context.SaveChangesAsync();

            }

            catch (DbUpdateConcurrencyException)

            {

                if (!QuestionsimgExists(questionsimg.Sno))

                {

                    return NotFound();

                }

                else

                {

                    throw;

                }

            }

            return RedirectToAction(nameof(Index));

        }

        return View(questionsimg);

    }
  
.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,923 questions
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,615 questions
0 comments No comments
{count} votes

Accepted answer
  1. AgaveJoe 28,536 Reputation points
    2024-07-05T17:36:44.2333333+00:00

    Database Contains images , when I try to edit the text , I need to upload images again , please suggest.

    The problem is your design saves everything the user submits.

    I would use standard MVC patterns (see any tutorial). First load the entity from the database using the Id submitted by the user. Next, overwrite the image arrays if the user uploaded a file. Finally save the entity not the model submitted by the user.

    Below is an example of the pattern. I did not test the code so yo might have to tweak it a bit but it should be enough to understand the pattern.

    public async Task<IActionResult> Edit(int id, [Bind("Sno,No,Topic,QuestionTitle,Opt1,Opt2,Opt3,Opt4,Answer,Time,Correct,Solution,Imagedata,Imagesol")] Questionsimg questionsimg, IFormFile imagedata, IFormFile imagesol)
    {
        var myEntity = _context.Questionsimg.FirstOrDefault(e => e.Sno = Id);
        
        if (myEntity == null || id != myEntity.Sno)
        {
            return NotFound();
        }
    
        if (imagedata != null)
        {
            if (imagedata.Length > 0)
            {
                using (var target = new MemoryStream())
                {
                    imagedata.CopyTo(target);
                    myEntity.Imagedata = target.ToArray();
                }
            }
        }
    
        if (imagesol != null)
        {
            if (imagesol.Length > 0)
            {
                using (var target = new MemoryStream())
                {
                    imagesol.CopyTo(target);
                    myEntity.Imagesol = target.ToArray();
                }
            }
        }
    
        if (ModelState.IsValid)
        {
            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!QuestionsimgExists(questionsimg.Sno))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }
            return RedirectToAction(nameof(Index));
        }
        return View(questionsimg);
    }
    
    

1 additional answer

Sort by: Most helpful
  1. Ping Ni-MSFT 4,720 Reputation points Microsoft Vendor
    2024-07-09T06:49:41.2+00:00

    Hi @Kalyan A,

    You cannot programmatically set chosen file in browser for security reasons. It would be a serious security flaw. The user must manually select a file through the file input field.

    You can find the database existed value by id and questionsimg.Sno, then set the image value to the variable(questionsimg) passed from frontend to make the update operation successfully:

    [HttpPost]
     [ValidateAntiForgeryToken]
     public async Task<IActionResult> Edit(int id, [Bind("Sno,No,Topic,QuestionTitle,Opt1,Opt2,Opt3,Opt4,Answer,Time,Correct,Solution,Imagedata,Imagesol")] Questionsimg questionsimg, IFormFile imagedata, IFormFile imagesol)
     {
         if (id != questionsimg.Sno)
         {
             return NotFound();
         }
         
         
        //add this...
         var existingQuestion = await _context.Questionsimg.AsNoTracking().FirstOrDefaultAsync(q => q.Sno == id);
         if (existingQuestion == null)
         {
             return NotFound();
         }
         if (imagedata != null && imagedata.Length > 0)
         {
             using (var target = new MemoryStream())
             {
                 imagedata.CopyTo(target);
                 questionsimg.Imagedata = target.ToArray();
             }
         }
         else
         {
             questionsimg.Imagedata = existingQuestion.Imagedata;    //add this...
         }
         if (imagesol != null && imagesol.Length > 0)
         {
             using (var target = new MemoryStream())
             {
                 imagesol.CopyTo(target);
                 questionsimg.Imagesol = target.ToArray();
             }
         }
         else
         { 
             questionsimg.Imagesol = existingQuestion.Imagesol;    //add this...
         }
         if (ModelState.IsValid)
         {
             try
             {
                 _context.Update(questionsimg);
                 await _context.SaveChangesAsync();
             }
             catch (DbUpdateConcurrencyException)
             {
                 if (!QuestionsimgExists(questionsimg.Sno))
                 {
                     return NotFound();
                 }
                 else
                 {
                     throw;
                 }
             }
             return RedirectToAction(nameof(Index));
         }
         return View(questionsimg);
     }
    

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Rena

    1 person found this answer helpful.

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.