Click here to Skip to main content
15,887,289 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I Can't do Function Create in asp core mvc, i make one VIew for Edit And Create but functon Edit is Working Well, but function Create didn't Save in database

C#
Class ClsItem


namespace books.BL
{
    public class ClsItem
    {
        public  StoreBooksContext booksContext=new StoreBooksContext();      

        public List<tbitem> GetAll()
        {
        
            List<tbitem> lstItems = booksContext.TbItems.
                OrderByDescending(a => a.ItemName).
                ThenByDescending(a => a.SalePrice).ToList();
            return lstItems;
        }

        public TbItem GetById(int id)
        {
            TbItem SelectedItem = booksContext.TbItems.FirstOrDefault(i => i.ItemId == id);
            return SelectedItem;
         
        }

        public bool AddToDataBase(TbItem item)
        {

            try
            {
                booksContext.TbItems.Add(item);
                booksContext.SaveChanges();
                return true;
            }
            catch (Exception)
            {

                throw;
            }
        }

        public bool Edit(TbItem item)
        {

            try
            {

                booksContext.Entry(item).State = EntityState.Modified;
                booksContext.SaveChanges();
                return true;
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
My ItemController
C#
namespace books.Areas.Admin.Controllers
{
    [Area("Admin")]
    public class ItemsController : Controller
    {
        public ClsItem clsItem = new ClsItem();

        public IActionResult List()
        {

            return View(clsItem.GetAll());
        }

        public IActionResult Edit(int? id)
        {
            ClsCategories clsCategories = new ClsCategories();
            ViewBag.clsCategoryList = clsCategories.GetAll();
            if (id != null)
            {
                return View(clsItem.GetById(Convert.ToInt32(id)));
            }
            else
            {
                return View();
            }

        }


     
        [HttpPost]
        public async Task <iactionresult> Save(TbItem item,List<iformfile> Files)
        {

            try
            {
                if (ModelState.IsValid)
                {

                    foreach (var file in Files)
                    {
                        if (file != null)
                        {
                            string ImageName = Guid.NewGuid().ToString() + ".jpg";
                            var filePaths = Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\Uploads", ImageName);
                            using (var stream = System.IO.File.Create(filePaths))
                            {
                                await file.CopyToAsync(stream);
                            }
                            item.ImageName = ImageName;
                        }
                    }

                    if (item.ItemId == 0)
                        clsItem.AddToDataBase(item);
                           
                    else
                    
                        clsItem.Edit(item);
                        return RedirectToAction("List", "Items");
                    
                }

                return RedirectToAction("List", "Items");
            }
            catch (Exception ex)
            {

                throw ex;
            }

           

        }
    }
}
My Edit View
HTML
@model TbItem

@{
    ViewData["Title"] = "Edit";
}

<h1>Edit</h1>

<div class="app-content content">
    <div class="content-overlay"></div>
    <div class="header-navbar-shadow"></div>
    <div class="content-wrapper">
        <div class="col-md-8 col-8">
            <div class="card" style="height: 419.75px">
                <div class="card-header">
                    <h4 class="card-title">Edit Form</h4>
                </div>
                <div class="card-content">
                    <div class="card-body">
                        
                            <div class="form-body">
                                <div class="row">
                                    <div class="col-12">
                                        <div class="form-group row">
                                            <div class="col-md-4">
                                                <span>Item Name</span>
                                            </div>
                                            <div class="col-md-8">

                                                
                                                
                                            </div>
                                        </div>
                                    </div>

                                    <div class="col-12">
                                        <div class="form-group row">
                                            <div class="col-md-4">
                                                <span>SalePrice</span>
                                            </div>
                                            <div class="col-md-8">
                                                
                                                
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-12">
                                        <div class="form-group row">
                                            <div class="col-md-4">
                                                <span>Purchase Price</span>
                                            </div>
                                            <div class="col-md-8">
                                                
                                                
                                            </div>

                                        </div>
                                    </div>

                                    <div class="col-12">
                                        <div class="form-group row">
                                            <div class="col-md-4">
                                                <span>Select Category</span>
                                            </div>
                                            <div class="col-md-8">
                                                
                                                
                                                
                                                
                                            </div>
                                        </div>
                                    </div>


                                    <div class="col-12">
                                        <div class="form-group row">
                                            <div class="col-md-2">
                                                <span>Item Image</span>
                                            </div>
                                            <div class="col-md-8">
                                                
                                            </div>
                                        </div>
                                    </div>

                                    <div class="form-group col-md-8 offset-md-4">

                                    </div>
                                    <div class="col-md-8 offset-md-4">
                                        

                                    </div>
                                </div>
                            </div>
                        
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>


What I have tried:

I Can't do Function Create in asp core mvc, i make one VIew for Edit And Create but functon Edit is Working Well, but function Create didn't Save in database

C#
Class ClsItem


namespace books.BL
{
public class ClsItem
{
public StoreBooksContext booksContext=new StoreBooksContext();

public List<tbitem> GetAll()
{

List<tbitem> lstItems = booksContext.TbItems.
OrderByDescending(a => a.ItemName).
ThenByDescending(a => a.SalePrice).ToList();
return lstItems;
}

public TbItem GetById(int id)
{
TbItem SelectedItem = booksContext.TbItems.FirstOrDefault(i => i.ItemId == id);
return SelectedItem;

}

public bool AddToDataBase(TbItem item)
{

try
{
booksContext.TbItems.Add(item);
booksContext.SaveChanges();
return true;
}
catch (Exception)
{

throw;
}
}

public bool Edit(TbItem item)
{

try
{

booksContext.Entry(item).State = EntityState.Modified;
booksContext.SaveChanges();
return true;
}
catch (Exception)
{

throw;
}
}
}
}
My ItemController
C#
namespace books.Areas.Admin.Controllers
{
[Area("Admin")]
public class ItemsController : Controller
{
public ClsItem clsItem = new ClsItem();

public IActionResult List()
{

return View(clsItem.GetAll());
}

public IActionResult Edit(int? id)
{
ClsCategories clsCategories = new ClsCategories();
ViewBag.clsCategoryList = clsCategories.GetAll();
if (id != null)
{
return View(clsItem.GetById(Convert.ToInt32(id)));
}
else
{
return View();
}

}



[HttpPost]
public async Task <iactionresult> Save(TbItem item,List<iformfile> Files)
{

try
{
if (ModelState.IsValid)
{

foreach (var file in Files)
{
if (file != null)
{
string ImageName = Guid.NewGuid().ToString() + ".jpg";
var filePaths = Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\Uploads", ImageName);
using (var stream = System.IO.File.Create(filePaths))
{
await file.CopyToAsync(stream);
}
item.ImageName = ImageName;
}
}

if (item.ItemId == 0)
clsItem.AddToDataBase(item);

else

clsItem.Edit(item);
return RedirectToAction("List", "Items");

}

return RedirectToAction("List", "Items");
}
catch (Exception ex)
{

throw ex;
}



}
}
}
Posted
Updated 15-May-21 3:59am
v3
Comments
Mo-Benali 16-May-21 10:24am    
What do you mean by "I Can't do Function Create"? Does it throw an exception? it's not working at all? if it does throw an exception, what is it?

1 solution

It looks like you have so much code it's wrapping over the button to add a comment so I'll add it here as a Solution instead.

1. Only post relevant code. It's hard to read through all of this code. For example, the Delete method is not relevant to your question. Click improve question and clean it up.
2. I don't see anywhere where it is calling your code to create the record.
3. Debug your code. Put breakpoints to make sure it's actually running what you think it is.
 
Share this answer
 

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