Wednesday, September 19, 2018

Published 2:13 AM by with 0 comment

AspNet Core MVC 2.1-Delete Action Method


In Asp.net Core the Delete Action is work as follows:

You Need To Create  Get or Post Method


Get Action:


        public async Task<IActionResult> Delete(int? id)
        {
            if (id== null)
            {
                return NotFound();
            }
            var s = await _dbContext.STUDENTINFO.AsNoTracking()
                .FirstOrDefaultAsync(m=>m.Id ==id);
            if(s == null)
            {
                return NotFound();
            }
            //if(saveChangesError.GetValueOrDefault)
            return View();
        }

Post Method:

[HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Delete(int? id, IFormCollection collection)
        {
            if (id == null)
            {
                return NotFound();
            }
            var s = await _dbContext.STUDENTINFO.AsNoTracking()
                .FirstOrDefaultAsync(m => m.Id == id);

            if (s == null)
            {
                return NotFound();
            }
            try
            {
                // TODO: Add delete logic here
                //var d= await _dbContext.STUDENTINFO.FindAsync(id);
                s.UpdatedBy = 1;
                s.UpdatedDateTime = DateTime.Now;
                await _studentInfoService.DeleteAsync(s);
                Flag = !Flag;
                return RedirectToAction(nameof(Index));
                
            }
            catch
            {
                return View();
            }
        }

Here you need to create a service pattern or Repository pattern but Its Optional
Remember:Repository Pattern is optional .

      edit

0 comments:

Post a Comment