Click here to Skip to main content
15,851,242 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +
I have a controller named Categories.
I have one form or One View for Create And Edit.
Create Action works well, but when I click Edit, the NewRow is added in database. The problem is I want to Edit Row without adding new in database.

What I have tried:

my Controller
C#
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using YourBook.Web.Core.Models;
using YourBook.Web.Core.ViewModels;
using YourBook.Web.Utilities;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;

namespace YourBook.Web.Controllers
{
    public class CategoriesController : Controller
    {
        private readonly ApplicationDbContext _context;
        public CategoriesController(ApplicationDbContext context)
        {
                _context = context;
        }
  
        public IActionResult Index()
        {
            //TODO Use ViewMOdel
            var ListCategories=_context.Categories.ToList();
            return View(ListCategories);
        }

        [HttpGet]
        public IActionResult Create()
        {          
            return View("Form");
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task< IActionResult> 
        Create(CategoryFormViewModel model, List<iformfile> Files) 
        {
            if (!ModelState.IsValid)
                return View("Form",model);

            var ObjCategory = new Category();
            ObjCategory.Name = model.Name;
            ObjCategory.ImageName = await Helper.UploadImage
                                    (Files, "Categories");
            _context.Categories.Add(ObjCategory);
            _context.SaveChanges();
            return RedirectToAction(nameof(Index));  
        }

        [HttpGet]
        public IActionResult Edit(int Id)
        {
            var catg = _context.Categories.Find(Id);
            if (catg is null)
                return NotFound();

            var ViewModel = new CategoryFormViewModel
            {
                Id = Id,
                Name= catg.Name,
                ImageName= catg.ImageName,
            };

            return View("Form",ViewModel);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
       public async Task< IActionResult> 
       Edit(CategoryFormViewModel model, List<iformfile> Files)
        {
            if (!ModelState.IsValid)
                return View("Form", model);

            var catg = await _context.Categories.FindAsync(model.Id);

            if (catg != null)
            {
                catg.Name = model.Name;
                catg.UpdatedOn = DateTime.Now;

                if (Files.Count > 0)
                {
                    catg.ImageName = await Helper.UploadImage
                                     (Files, "Categories");
                }

                _context.Entry(catg).State = EntityState.Modified;
                await _context.SaveChangesAsync();
            }

            return RedirectToAction(nameof(Index));
        }
    }
}


My View

Razor
@model CategoryFormViewModel

@{ViewData["Title"]=$"{(Model?.Id>0 ? "Edit" : "AddNew")} Category";}
<div class="content-wrapper">
    <div class="page-header">
        <h3 class="page-title"> Form elements </h3>
        
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="#">Forms</a></li>                <li class="breadcrumb-item active">Form elements</li>            </ol>
        
    </div>
    <div class="row">
        <div class="col-md-8 grid-margin stretch-card">
            <div class="card">
                <div class="card-body">
                    <h4 class="card-title">Default form</h4>
                    <p class="card-description"> 
                    Basic form layout </p>
                    
                        @if (Model?.Id > 0)
                        {
                            
                        }

                        <div class="form-group">
                            @ResAdmin.lblCategoryName
                            
                            <span></span>
                        </div>

                        <div class="form-group">
                            
                                @ResAdmin.lblImage                            
                            
                            <span></span>

                        </div>

                        @ResGeneral.lblSave
                        @ResGeneral.lblNew
                    
                </div>
            </div>
        </div>

        <div class="col-md-4 grid-margin stretch-card">
            <div class="card">
                <div class="card-body">
                    <span id="tbImgName"></span>
                    <div id="tbImgSrc">
                        @if (Model != null && Model.ImageName != null)
                        {
                            
                        }
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

@section Scripts
{    
        var Upload = {
            UploadDefaultImg: function(e) {
                const file = e.target.files[0];
                const reader = new FileReader();
                reader.onloadend = () => {
                    CourseMediaImgName = file.name;
                    CourseMediaImgBase64 = 
                    reader.result.slice(reader.result.indexOf('base64,') + 7);
                    $("#tbImgName").html(file.name)
                    $("#tbImgSrc").html(`<img class="thumbnail" 
                    src = "${reader.result}"  
                    style = "width: 200px;height: 300px;
                    border-radius: 5px;border: 1px solid #d9d9d9;
                    padding: 1px;" />`)
                };
                reader.readAsDataURL(file);
            }
    }    
}
Posted
Updated 5-Nov-23 1:30am
v3
Comments
Richard Deeming 30-Oct-23 6:10am    
Where's the <form> element / Html.BeginForm call?

The most likely cause is that you're posting to the wrong action. But without seeing how you've defined the form, that's just a guess.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900