Wednesday 21 August 2019

CRUD operations using CORE(2.1) MVC6 ,Generic Repository & Dependency Injection, EF code first approach , jquery datatable & Modal popup.





 Models :

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

namespace WebApplication1.Models
{
    public class DEPT
    {
        [Key]
        public int DID { get; set; }
        [MaxLength(50)]
        public string DNAME { get; set; }
        [MaxLength(50)]
        public string LOCATION { get; set; }
    }
}

AppDbContext.cs :

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

namespace WebApplication1.Models
{
    public class AppDbContext : DbContext
    {
        public AppDbContext(DbContextOptions<AppDbContext> options):base(options)
        { }
        public DbSet<DEPT> DEPT { get; set; }
    }
}

Generic Repository :

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


namespace WebApplication1.Models
{
    public interface IRepository <T> where T : class
    {
        IQueryable<T> Gets();
        Task<T> Get(int t);
        Task Save(T t);
        Task Update(T t);
        Task Delete(int t);
    }
}

Implement Repository :

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

namespace WebApplication1.Models
{
    public class Repository<T> : IRepository<T> where T : class
    {
        private readonly AppDbContext context;
        

        public Repository(AppDbContext Context)
        {
            this.context = Context;
        }

        public async Task Delete(int t)
        {
            var data = await Get(t);
            context.Set<T>().Remove(data);
            await context.SaveChangesAsync();
        }

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

        public IQueryable<T> Gets()
        {
            return context.Set<T>().AsNoTracking();
        }

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

        public async Task Update(T t)
        {
            context.Set<T>().Update(t);
            await context.SaveChangesAsync();
        }

       
    }
}


Add connection string in appsettings.json :

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "DBConnection": "server=(localdb)\\MSSQLLocalDB;database=sivdb;Trusted_Connection=true"
  }
}

Register Dependency Injection in dependency  container Startup.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using WebApplication1.Models;

namespace WebApplication1
{
    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.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddMvc();
            //services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddDbContextPool<AppDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DBConnection")));
            services.AddScoped<IRepository<DEPT>, Repository<DEPT>>();

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Rest}/{action=Index}/{id?}");
            });
        }
    }
}

Use 2 commands for migration :
Add-Migration Intialmigraion
Update-Database

View Model :

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

namespace WebApplication1.Models
{
    public class DEPTVM
    {
       
        public int DID { get; set; }
        [Display(Name ="Department Name")]
        [Required(ErrorMessage = "Department name should not be blank.")]
        public string DNAME { get; set; }
        [Required(ErrorMessage = "Location should not be blank.")]
        [Display(Name ="Location")]
        public string LOCATION { get; set; }
    }
}

Controller :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;

namespace WebApplication1.Controllers
{
    public class RestController : Controller
    {
        private readonly IRepository<DEPT> iRepository;
        public RestController(IRepository<DEPT> Irepository)
        {
            this.iRepository = Irepository;
        }
        [HttpGet]
        public IActionResult Index()
        {
            return View(iRepository.Gets());
        }
        [HttpGet]
        public IActionResult Openpopup(int id)
        {
            DEPTVM vm = new DEPTVM();
            if (id != 0)
            {
                DEPT dept = iRepository.Get(id).Result;
                vm.DID = dept.DID;
                vm.DNAME = dept.DNAME;
                vm.LOCATION = dept.LOCATION;
            }
            return PartialView("Add", vm);
        }
        [HttpGet]
        public IActionResult Delete(int id)
        {
            iRepository.Delete(id);
            return Json("1");
        }
        [HttpPost]
        public IActionResult Create(DEPTVM vm)
        {
            if (ModelState.IsValid)
            {
                DEPT dept = new DEPT();
                if (vm.DID != 0)
                {
                    dept = iRepository.Get(vm.DID).Result;
                    dept.DNAME = vm.DNAME;
                    dept.LOCATION = vm.LOCATION;
                    iRepository.Update(dept);
                }
                else
                {
                    dept.DNAME = vm.DNAME;
                    dept.LOCATION = vm.LOCATION;
                    iRepository.Save(dept);
                }
                
               
            }
            return RedirectToAction("Index");
        }

    }
}

Index View :

@model IEnumerable<WebApplication1.Models.DEPT>

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



<p style="margin-top:10px">
    <input type="button" class="btn btn-primary" value="Add New" style="width:80px" id="add" />
</p>
<div style="border:1px solid #000000">
    <table id="tb" class="table table-responsive table-hover table-striped">
        <thead class="bg bg-primary">
            <tr>
                <th>
                    @Html.DisplayNameFor(model => model.DID)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.DNAME)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.LOCATION)
                </th>
                <th>ACTION</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in Model)
            {
                <tr>
                    <td>
                        @Html.DisplayFor(modelItem => item.DID)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.DNAME)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.LOCATION)
                    </td>
                    <td>
                        <a class="edit">Edit</a> | <a class="delete">Delete</a>
                    </td>
                </tr>
            }
        </tbody>
    </table>

</div>
<div id="dmldv">
    
</div>
<div id="delForm" style="display:none">
    <h1>Do you want to delete it ?</h1>
</div>

<style type="text/css">
    .ui-dialog {
        height: auto;
        width: 700px;
        top: 60px !important;
        left: 675px;
    }

    .ui-dialog-titlebar-close {
        background: url("http://code.jquery.com/ui/1.10.3/themes/smoothness/images/ui-icons_888888_256x240.png") repeat scroll -93px -128px rgba(0, 0, 0, 0);
        border: medium none;
    }

        .ui-dialog-titlebar-close:hover {
            background: url("http://code.jquery.com/ui/1.10.3/themes/smoothness/images/ui-icons_222222_256x240.png") repeat scroll -93px -128px rgba(0, 0, 0, 0);
        }
</style>
@section Scripts {

    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
    <script type="text/javascript">
        var createMode = $("#dmldv").dialog({
            autoOpen: false,
            modal: true,
            height: 350,
            width: 700,
            resizable: false,
            position: { my: "center", at: "center", of: $("body"), within: $("body") },
            show: { effect: 'blind', speed: 1000 },
            hide: { effect: 'blind', speed: 1000 },
            title: "Add Or Edit"

        });
        var Delform = $("#delForm");
        $(function () {
            var id = 0;
            var table = $("#tb").DataTable({
                "order": [[0, "asc"]],
                "lengthMenu": [[2, 10, 25, 50, -1], [2, 10, 25, 50, "All"]],
                "scroller": true,
                "orderClasses": false,
            })
            $('#tb').on("click", ".delete", function () {
                id = $(this).closest("tr").find("td:eq(0)").text();
                Delform.dialog({
                    autoOpen: false,
                    modal: true,
                    width: 550,
                    title: "Delete",
                    resizable: false,
                    position: { my: "center", at: "center", of: $("body"), within: $("body") },
                    show: { effect: 'blind', speed: 1000 },
                    hide: { effect: 'blind', speed: 1000 },

                    buttons: {
                        Yes: function () {

                            $.ajax({
                                "url": '@Url.Action("Delete", "Rest")',
                                type: 'Get',
                                datatype: 'json',
                                cache: false,
                                data: { id: id },
                                success: function (data) {
                                    Delform.dialog("close");
                                    window.location.reload(true);
                                },
                                error: function (t) {
                                    alert(t.responseText);
                                }
                            });


                        },
                        No: function () {
                            Delform.dialog("close");
                        }

                    }

                });

                Delform.dialog("open");

            });
            $('#tb').on("click", ".edit", function () {
                 id = $(this).closest("tr").find("td:first").text();
                fillpopup(id);
            });
            function fillpopup(ID) {
                $.ajax({
                    "url":  '@Url.Action("Openpopup", "Rest")',
                    type: 'Get',
                    datatype: 'json',
                    cache: false,
                    async: true,
                    data: {id:ID},
                    success: function (data) {
                        createMode.empty().append(data);
                        createMode.dialog("open");
                    },
                    error: function (t) {
                        alert(t.responseText);
                    }
                });
            }
            $('#add').click(function () {
                fillpopup(0);
            })
        });
        
    </script>

    }

Add Or Edit View :

@model DEPTVM


<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="DNAME" class="control-label"></label>
                <input asp-for="DNAME" class="form-control" />
                <input type="hidden" asp-for="DID"  />
                <span asp-validation-for="DNAME" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="LOCATION" class="control-label"></label>
                <input asp-for="LOCATION" class="form-control" />
                <span asp-validation-for="LOCATION" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </form>
    </div>
</div>

<script src="~/lib/jquery-validation/dist/jquery.validate.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}


Layout View :

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@ViewData["Title"] - WebApplication1</title>

    <environment include="Development">
        <link href="~/css/jquery-ui.css" rel="stylesheet" />
        <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
        <link rel="stylesheet" href="~/css/site.css" />
        <link href="~/css/DataTables/css/jquery.dataTables.css" rel="stylesheet" />
        <link href="~/css/DataTables/css/jquery.dataTables_themeroller.css" rel="stylesheet" />
    </environment>
    <environment exclude="Development">
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
              asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"
              asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute" />
        <link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" />
    </environment>
</head>
<body>
    <nav class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a asp-area="" asp-controller="Home" asp-action="Index" class="navbar-brand">WebApplication1</a>
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li><a asp-area="" asp-controller="Home" asp-action="Index">Home</a></li>
                    <li><a asp-area="" asp-controller="Home" asp-action="About">About</a></li>
                    <li><a asp-area="" asp-controller="Home" asp-action="Contact">Contact</a></li>
                </ul>
            </div>
        </div>
    </nav>

    <partial name="_CookieConsentPartial" />

    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; 2019 - WebApplication1</p>
        </footer>
    </div>

    <environment include="Development">
        <script src="~/lib/jquery/dist/jquery.js"></script>
        <script src="~/js/jquery-ui.js"></script>
        <script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>

        <script src="~/js/DataTables/jquery.dataTables.js"></script>
        <script src="~/js/site.js" asp-append-version="true"></script>

    </environment>
    <environment exclude="Development">
        <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.3.1.min.js"
                asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
                asp-fallback-test="window.jQuery"
                crossorigin="anonymous"
                integrity="sha384-tsQFqpEReu7ZLhBV2VZlAu7zcOV+rXbYlF2cqB8txI/8aZajjp4Bqd+V6D5IgvKT">
        </script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"
                asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.min.js"
                asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal"
                crossorigin="anonymous"
                integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd">
        </script>
        <script src="~/js/site.min.js" asp-append-version="true"></script>
    </environment>

    @RenderSection("Scripts", required: false)
</body>
</html>








No comments:

Post a Comment