Saturday 16 May 2020

CRUD operations using CORE(3.1) MVC,Generic Repository & Dependency Injection, core EF code first approach ,Bootstrap modal popup.


Dot net core code :

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace BootstarpModalPopup.Models
{
    public class CUSTOMER
    {
        [Key]
        public int CID { get; set; }
        [MaxLength(50)]
        public string NAME { get; set; }
        public string ADDRESS { get; set; }
    }
}
--
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace BootstarpModalPopup.Models
{
    public class CUSTOMERVM
    {
        public CUSTOMERVM()
        {
            CustomerList = new List<CUSTOMER>();
        }
        public int CID { get; set; }
        [Required(ErrorMessage ="Name should not be blank.")]
        public string NAME { get; set; }
        [Required(ErrorMessage = "Address should not be blank.")]
        [DataType(DataType.MultilineText)]
        public string ADDRESS { get; set; }
        public string Message { get; set; }
        public List<CUSTOMER> CustomerList { get; set; }

    }
}
--
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;

namespace BootstarpModalPopup.Models
{
    public class AppDbContext:DbContext
    {
        public AppDbContext(DbContextOptions<AppDbContext> options):base(options)
        {
        }
        public DbSet<CUSTOMER> Customers { get; set; }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer(@"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=SivDB008;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False");
        }
    }
}
--
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BootstarpModalPopup.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.EntityFrameworkCore;

namespace BootstarpModalPopup
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            services.AddDbContext<AppDbContext>();
            services.AddScoped<IRepository<CUSTOMER>, Repository<CUSTOMER>>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}
--
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace BootstarpModalPopup.Models
{
   public interface IRepository<T> where T:class
    {
        Task<IEnumerable<T>> Gets();
        Task<T> Get(int ID);
        Task<T> Save(T t);
        Task<T> Update(T t);
        Task<T> Delete(int ID);
        Task<T> SaveAll(List<T> lst);
        Task<T> DeleteAll(List<T> lst);
    }
}
--
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;

namespace BootstarpModalPopup.Models
{
    public class Repository<T> : IRepository<T> where T : class
    {
        #region Declaretion
        private readonly AppDbContext Context;
        #endregion
        public Repository(AppDbContext Context)
        {
            this.Context = Context;    
        }
        public async Task<T> Delete(int ID)
        {
            T t =await Context.Set<T>().FindAsync(ID);
            Context.Set<T>().Remove(t);
            await Context.SaveChangesAsync();
            return t;
        }

        public async Task<T> DeleteAll(List<T> lst)
        {
            Context.Set<T>().RemoveRange(lst);
            await Context.SaveChangesAsync();
            return lst.FirstOrDefault();
        }

        public async Task<T> Get(int ID)
        {
            return await Context.Set<T>().FindAsync(ID);
        }

        public async Task<IEnumerable<T>> Gets()
        {
            return await Context.Set<T>().ToListAsync();
        }

        public async Task<T> Save(T t)
        {
            await Context.Set<T>().AddAsync(t);
            await Context.SaveChangesAsync();
            return t;
        }

        public async Task<T> SaveAll(List<T> lst)
        {
            await Context.Set<T>().AddRangeAsync(lst);
            await Context.SaveChangesAsync();
            return lst.FirstOrDefault();
        }

        public async Task<T> Update(T t)
        {
            Context.Set<T>().Update(t);
            await Context.SaveChangesAsync();
            return t;
        }
    }
}
--
Controller :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using BootstarpModalPopup.Models;

namespace BootstarpModalPopup.Controllers
{
    public class CustomerController : Controller
    {
        #region
        private readonly IRepository<CUSTOMER> repository;
        private static string message = string.Empty;
        #endregion
        public CustomerController(IRepository<CUSTOMER> repository)
        {
            this.repository = repository;   
        }
        [HttpGet]
        public async Task<IActionResult> Index(int? id)
        {
            CUSTOMERVM cUSTOMERVM = new CUSTOMERVM();
            try
            {
                if(id==null)
                cUSTOMERVM.Message = string.Empty;
                else
                {
                    CUSTOMER cUSTOMER = await repository.Get(id.Value);
                    cUSTOMERVM.CID = cUSTOMER.CID;
                    cUSTOMERVM.NAME = cUSTOMER.NAME;
                    cUSTOMERVM.ADDRESS = cUSTOMER.ADDRESS;
                }
                var data = await repository.Gets();
                cUSTOMERVM.CustomerList = data.ToList();
                if (!string.IsNullOrEmpty(message))
                {
                    cUSTOMERVM.Message = message;
                    message = null;
                }
                else
                    cUSTOMERVM.Message = "";
            }
            catch (Exception ex)
            {

                cUSTOMERVM.Message = ex.Message;
            }
            
            return View(cUSTOMERVM);
        }
        [HttpPost]
        public async Task<IActionResult> Create(CUSTOMERVM cUSTOMERVM)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    CUSTOMER cUSTOMER = new CUSTOMER();
                    if (cUSTOMERVM.CID>0)
                    {
                        cUSTOMER.CID = cUSTOMERVM.CID;
                        cUSTOMER.NAME = cUSTOMERVM.NAME;
                        cUSTOMER.ADDRESS = cUSTOMERVM.ADDRESS;
                        cUSTOMER = await repository.Update(cUSTOMER);
                        message = "Data Updated Successfully.";
                        return RedirectToAction("Index");
                    }
                    else
                    {
                     
                        cUSTOMER.NAME = cUSTOMERVM.NAME;
                        cUSTOMER.ADDRESS = cUSTOMERVM.ADDRESS;
                        cUSTOMER = await repository.Save(cUSTOMER);
                        message = "Data Saved Successfully.";
                        return RedirectToAction("Index");
                    }
                }
                else
                    return View(cUSTOMERVM);
            }
            catch (Exception ex)
            {
                cUSTOMERVM.Message = ex.Message;
            }
            return View(cUSTOMERVM);
        }

        [HttpGet]
        public async Task<IActionResult> Delete(int id)
        {
            CUSTOMER cUSTOMER = await repository.Delete(id);
            message = "Data Deleted Successfully.";
            return RedirectToAction("Index");
        }

    }
}

Index View :
@model CUSTOMERVM

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

    <style type="text/css">
        .xxx {
            background-color: #0069d9;
            border-color: #0062cc;
            color: white
        }

        .modal-header {
            display: block !important;
        }

        .modal-title {
            float: left;
        }

        .modal-header .close {
            float: right;
        }
    </style>
<div class="row">
    <div class="col-md-4">
        <form asp-action="Create">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>

            <div class="form-group">
                <label asp-for="NAME" class="control-label"></label>
                <input asp-for="NAME" class="form-control" />
                <input asp-for="CID" type="hidden" />
                <span asp-validation-for="NAME" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="ADDRESS" class="control-label"></label>
                <textarea asp-for="ADDRESS" class="form-control"></textarea>
                <span asp-validation-for="ADDRESS" class="text-danger"></span>
            </div>
            
            <div class="form-group">
                <input type="submit" value="Submit" class="btn btn-primary" style="width:80px" />
                <input type="reset" value="Reset" class="btn btn-primary" style="width:80px"/>
            </div>
        </form>
    </div>
</div>
<div class="row">
    <partial name="ListPV" model="Model.CustomerList" />
</div>
<partial name="ConfirmPV" />
@{
    if (@Model.Message != "")
    {
        <partial name="AlertPV" model='new Alert() { Message=Model.Message }' />
    }
}

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

ListPV Partial View :

@model IEnumerable<BootstarpModalPopup.Models.CUSTOMER>


<table class="table table-bordered table-hover">
    <thead class="xxx">
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.CID)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.NAME)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.ADDRESS)
            </th>
            <th>ACTION</th>
        </tr>
    </thead>
    <tbody>
        @if (Model.Count() > 0)
        {
            @foreach (var item in Model)
            {
                <tr>
                    <td>
                        @Html.DisplayFor(modelItem => item.CID)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.NAME)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.ADDRESS)
                    </td>
                    <td>
                        @Html.ActionLink("Edit", "Index", new { id = item.CID }) |
                        <a href="#" onclick="confirmDelete('@Url.Content("~/Customer/Delete/" + item.CID)')">Delete</a>
                    </td>
                </tr>
            }
        }
        else
        {
            <tr><td colspan="4" style="text-align:center; color:#d92424">NO RECORD FOUND</td></tr>
        }
    </tbody>
</table>

First add this partial view in the share folder 

@model Alert


<div class="modal fade" id="successModal" data-keyboard="false" data-backdrop="static" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                <h4 class="modal-title" id="myModalLabel">Alert Message</h4>
            </div>
            <div class="modal-body">
                @Html.DisplayFor(m => m.Message)
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary focusedButton" data-dismiss="modal">Ok</button>
            </div>
        </div>
    </div>
</div>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.min.js"></script>
<script type="text/javascript">
    $('#successModal').modal('show')
    $('body').keypress(function (e) {
        if (e.which === 13) {
            $(".focusedButton").trigger('click');
        }
    });
</script>

Again  add this partial view in the share folder 

<div class="modal fade" id="deleteModal" data-keyboard="false" data-backdrop="static" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                <h4 class="modal-title" id="myModalLabel">Confirmation Message</h4>
            </div>
            <div class="modal-body">
                Do you want to delete it. ?
            </div>
            <div class="modal-footer">
                <a id="deleteConfirm" href="#" class="btn btn-primary" style="width:80px">Yes</a>
                <button type="button" class="btn btn-primary focusedButton" data-dismiss="modal" style="width:80px">No</button>
            </div>
        </div>
    </div>
</div>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.min.js"></script>
<script type="text/javascript">
    var x = $('#deleteModal');
    function confirmDelete(url) {
        $("#deleteConfirm").attr("href", url);
        x.modal('show')
    }
    $('body').keypress(function (e) {
        if (e.which === 13) {
            $(".focusedButton").trigger('click');
        }
    });
</script>

MVC5 way :

C# code :

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace MicrosoftStyleMVC.Models
{
    public class EMP
    {
        [Key]
        public int EID { get; set; }
        [MaxLength(50)]
        public string NAME { get; set; }
        public string ADDRESS { get; set; }
    }
}
--
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace MicrosoftStyleMVC.Models
{
    public class EMPVM
    {
        public int EID { get; set; }
        [Required(ErrorMessage ="Name should not be blank.")]
        public string NAME { get; set; }
        [DataType(DataType.MultilineText)]
        [Required(ErrorMessage = "Address should not be blank.")]
        public string ADDRESS { get; set; }
        public string MESSAGE { get; set; }
    }
}
--
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace MicrosoftStyleMVC.Models
{
    public class AppDbContext:DbContext
    {
        public AppDbContext():base("Con")
        {
           // Database.SetInitializer(new DropCreateDatabaseAlways<AppDbContext>());
        }
        public DbSet<EMP> Emps { get; set; }
        public DbSet<DEPT> Depts { get; set; }
        public DbSet<COUNTRY> Countries { get; set; }
    }
}
--
Add connection string in web.confic file

<connectionStrings>
    <add name="con" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;database=MicrosoftMvc;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"  providerName="System.Data.SqlClient"/>
  </connectionStrings>
---

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MicrosoftStyleMVC.Models;
using System.Threading.Tasks;
using System.Data.Entity;

namespace MicrosoftStyleMVC.Controllers
{
    public class EmpController : Controller
    {
        private static string message;
        [HttpGet]
        public ActionResult Index(int? id)
        {
            EMPVM eMPVM = new EMPVM();
            EMP emp = null;
            if (id > 0)
            {
                using (AppDbContext obj = new AppDbContext())
                {
                    emp = obj.Emps.Find(id);
                    eMPVM.EID = emp.EID;
                    eMPVM.NAME = emp.NAME;
                    eMPVM.ADDRESS = emp.ADDRESS;
                }
            }
            if (!string.IsNullOrEmpty(message))
            {
                eMPVM.MESSAGE = message;
                message = null;
            }
            else
                eMPVM.MESSAGE = null;
            return View(eMPVM);
        }
        [HttpPost]
        [ValidateAntiForgeryToken()]
        public async Task<ActionResult> Index(EMPVM vm)
        {
            EMP emp = new EMP();
            using (AppDbContext obj = new AppDbContext())
            {
                if (vm.EID > 0)
                {

                    emp = obj.Emps.Find(vm.EID);
                    emp.NAME = vm.NAME;
                    emp.ADDRESS = vm.ADDRESS;
                    obj.Entry(emp).State = EntityState.Modified;
                    await obj.SaveChangesAsync();
                    message = "Data Updated Successfully.";

                }
                else
                {
                    emp.NAME = vm.NAME;
                    emp.ADDRESS = vm.ADDRESS;
                    obj.Entry(emp).State = EntityState.Added;
                    await obj.SaveChangesAsync();
                    message = "Data Saved Successfully.";
                }

            }
            return RedirectToAction("Index", new { id = 0 });
        }
        [HttpGet]
        [ChildActionOnly]
        public ActionResult List()
        {
            using (AppDbContext obj = new AppDbContext())
            {

                return View(obj.Emps.ToList());
            }

        }
        [HttpGet]
        public async Task<ActionResult> Delete(int id)
        {
            using (AppDbContext obj = new AppDbContext())
            {
                obj.Entry(obj.Emps.Find(id)).State = EntityState.Deleted;
                await obj.SaveChangesAsync();
                message = "Data Deleted Successfully.";
                return RedirectToAction("Index");
            }

        }
    }
}
--
Index view :

@model MicrosoftStyleMVC.Models.EMPVM
@using MicrosoftStyleMVC.Models

@{
    ViewBag.Title = "Index";
}


<div class="row">
    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()

        <div class="form-horizontal">

            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            <div class="form-group">
                @Html.LabelFor(model => model.NAME, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.HiddenFor(m=>m.EID)
                    @Html.EditorFor(model => model.NAME, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.NAME, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.ADDRESS, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.ADDRESS, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.ADDRESS, "", new { @class = "text-danger" })
                </div>
            </div>

         

            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Submit" class="btn btn-primary" style="width:80px" />
                    <input type="reset" value="Reset" class="btn btn-primary" style="width:80px" />
                </div>
            </div>
        </div>
    }

</div>
<div class="row">
    @Html.Action("List")
</div>
@{Html.RenderPartial("ConfirmPV"); }
@{
    if(Model.MESSAGE!=null)
    {
        @Html.Partial("AlertPV", new Alert() { Message=Model.MESSAGE  })
    }
}


@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

List View :

@model IEnumerable<MicrosoftStyleMVC.Models.EMP>

@{
    ViewBag.Title = "List";
    Layout = null;
}



<table class="table table-bordered table-condensed table-hover table-responsive table-striped" >
    <thead class="bg bg-primary">
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.NAME)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.ADDRESS)
            </th>
            <th>ACTION</th>
        </tr>
    </thead>
    <tbody>
        @{
            if (Model.Count() > 0)
            {

                foreach (var item in Model)
                {
                    <tr>
                        <td>
                            @Html.DisplayFor(modelItem => item.NAME)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.ADDRESS)
                        </td>
                        <td>
                            @Html.ActionLink("Edit", "Index", new { id = item.EID }) |
                            <a href="#" onclick="confirmDelete('@Url.Content("~/Emp/Delete/" + item.EID)')">Delete</a>
                            
                        </td>
                    </tr>
                }
            }
            else
            {
                <tr><td colspan="3" class="text-danger text-center">No Record(s) Found.</td></tr>
            }
        }

    </tbody>
    


</table>






No comments:

Post a Comment