Monday, 16 September 2019

CRUD operations using CORE(2.1) MVC6 , EF database first approach & Session.




To install Microsoft.AspNet.Session, run the following command in the Package Manager Console


sess





Starts.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.Extensions.Configuration;


using Microsoft.Extensions.DependencyInjection;




namespace WebApplication2


{


    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().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);


           services.AddSession();


           


        }




        // 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.UseSession();


            app.UseMvc(routes =>


            {


                routes.MapRoute(


                    name: "default",


                    template: "{controller=JBS}/{action=Index}/{id?}");


            });


        }


    }


}




Models :


using System;


using System.Collections.Generic;




namespace WebApplication2.DAL


{


    public partial class Emp1


    {


        public int Eid { get; set; }


        public string Name { get; set; }


        public int? Did { get; set; }


    }


}




using System;


using System.Collections.Generic;




namespace WebApplication2.DAL


{


    public partial class Dept


    {


        public int Did { get; set; }


        public string Dname { get; set; }


    }


}




View Model :






using System;


using System.Collections.Generic;


using System.Linq;


using System.Threading.Tasks;


using WebApplication2.DAL;




namespace WebApplication2.Models


{


    public class EMPVM3


    {


        public Dept DEPT { get; set; }


        public Emp1 EMP { get; set; }


        public List<Emp1> LEMP { get; set; }


        public EMPVM3()


        {


            LEMP = new List<Emp1>();


        }


    }


}




Create a new database in the server.

Go to Tools menu –> NuGet Package Manager –> Package Manager Console
And then run the following command to create a model from the existing database:

Scaffold-DbContext "Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Sankar;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False" Microsoft.EntityFrameworkCore.SqlServer -OutputDir DAL


Controller :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication2.Models;
using WebApplication2.DAL;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;

namespace WebApplication2.Controllers
{
    public class JBSController : Controller
    {
        [HttpGet]
        public IActionResult Index()
        {
            using (SankarContext obj = new SankarContext())
            {
                return View(obj.Dept.ToList());
            }

        }
        [HttpGet]
        public IActionResult Edit(int id)
        {
            EMPVM3 vm = new EMPVM3();
            using (SankarContext obj = new SankarContext())
            {
                
                vm.DEPT = obj.Dept.Find(id);
                vm.LEMP = obj.Emp1.Where(x => x.Did == id).ToList();
            }
            return View(vm);
        }
        [HttpGet]
        public IActionResult Create(int? id)
        {

            EMPVM3 vm = new EMPVM3();
            if (id != null)
            {
                var data = HttpContext.Session.GetString("abc");
                if (data != null)
                    vm = JsonConvert.DeserializeObject<EMPVM3>(data);
                vm.EMP = new Emp1();
            }
           

            return View(vm);
        }
        [HttpGet]
        public async Task<IActionResult> Save(EMPVM3 vm)
        {
            using (SankarContext obj = new SankarContext())
            {
                Dept dept = new Dept();
                dept.Did = vm.DEPT.Did;
                dept.Dname = vm.DEPT.Dname;
                await obj.Dept.AddAsync(dept);
                await obj.SaveChangesAsync();
                await obj.Emp1.AddRangeAsync(vm.LEMP.Select(m => new Emp1 { Eid=m.Eid, Name=m.Name, Did=vm.DEPT.Did }));
                await obj.SaveChangesAsync();
            }
            return RedirectToAction("Index");
        }
        [HttpGet]
        public async Task<IActionResult> Update(EMPVM3 vm)
        {
            using (SankarContext obj = new SankarContext())
            {
                Dept dept = obj.Dept.Find(vm.DEPT.Did);
                dept.Dname = vm.DEPT.Dname;
                obj.Dept.Update(dept);
                await obj.SaveChangesAsync();
                obj.Emp1.UpdateRange(vm.LEMP.Select(m => new Emp1 { Eid = m.Eid, Name = m.Name, Did = vm.DEPT.Did }));
                await obj.SaveChangesAsync();
            }
            return RedirectToAction("Index");
        }
        [HttpGet]
        public async Task<IActionResult> Delete(int id)
        {
            using (SankarContext obj = new SankarContext())
            {
                obj.Dept.Remove(obj.Dept.Find(id));
                await obj.SaveChangesAsync();
                obj.Emp1.RemoveRange(obj.Emp1.Where(m => m.Did == id).ToList());
                await obj.SaveChangesAsync();
            }
            return RedirectToAction("Index");
        }



        [HttpGet]
        public IActionResult Add(EMPVM3 vm)
        {
            vm.LEMP.Add(new Emp1 { Eid = vm.EMP.Eid, Name = vm.EMP.Name });
            var m = JsonConvert.SerializeObject(vm);
            HttpContext.Session.SetString("abc", m);
            return RedirectToAction("Create",new {id=1 });
        }
        [HttpGet]
        public IActionResult Remove(int id)
        {
            EMPVM3 vm = new EMPVM3();
            var data = HttpContext.Session.GetString("abc");
            if (data != null)
                vm = JsonConvert.DeserializeObject<EMPVM3>(data);
            vm.LEMP.Remove(vm.LEMP.SingleOrDefault(n=>n.Eid==id));
            var m = JsonConvert.SerializeObject(vm);
            HttpContext.Session.SetString("abc", m);
            return RedirectToAction("Create", new { id = 1 });
        }



    }
}

Index View :

@model IEnumerable<WebApplication2.DAL.Dept>

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



<p>
    <a asp-action="Create">Create New</a>
</p>
<table class="table table-bordered table-condensed table-hover table-responsive table-striped">
    <thead class="bg bg-primary">
        <tr>
            <th>
                DID
            </th>
            <th>
                DNAME
            </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.ActionLink("Edit", "Edit", new { id=item.Did }) |
                @Html.ActionLink("Delete", "Delete", new { id=item.Did })
            </td>
        </tr>
}
    </tbody>
</table>

Create View :

@model WebApplication2.Models.EMPVM3

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

<div class="row">
    <form class="form-horizontal">
        <div class="form-group">
            <label class="control-label col-lg-4" asp-for="DEPT.Did"></label>
            <div class="col-lg-4">
                <input class="form-control" asp-for="DEPT.Did" />
            </div>
        </div>
        <div class="form-group">
            <label class="control-label col-lg-4" asp-for="DEPT.Dname"></label>
            <div class="col-lg-4">
                <input class="form-control" asp-for="DEPT.Dname" />
            </div>
        </div>
        <div class="form-group">
            <label class="control-label col-lg-4"></label>
            <div class="col-lg-4">
                <table width="100%" cellpadding="1" cellspacing="1">
                    <tr><th>EID</th><th>NAME</th><th></th></tr>
                    @{


                        <tr><td><input class="form-control" asp-for="EMP.Eid" id="Eid" /></td><td><input class="form-control" asp-for="EMP.Name" /></td><td><input type="submit" asp-action="Add" asp-controller="JBS" value="Add" name="Add" style="width:80px" class="btn btn-primary" /></td></tr>

                        if (Model.LEMP.Count != 0)
                        {
                            for (int i = 0; i < Model.LEMP.Count; i++)
                            {
                                <tr><td><input class="form-control" asp-for="@Model.LEMP[i].Eid" /></td><td><input class="form-control" asp-for="@Model.LEMP[i].Name" /></td><td><input asp-action="Remove" asp-controller="JBS" asp-route-id="@Model.LEMP[i].Eid" value="Remove" type="submit" style="width:80px" name="Remove" class="btn btn-primary" /></td></tr>
                            }
                        }
                    }
                </table>
            </div>
        </div>
        <div class="form-group">
            <label class="control-label col-lg-4"></label>
            <div class="col-lg-4">
                <input type="submit" value="Save" style="width:80px" name="Save" asp-action="Save" asp-controller="JBS"  class="btn btn-primary" />
            </div>
            </div>  
    </form>
</div>

<div>
    <a asp-action="Index">Back to List</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
    <script type="text/javascript">
        $(function () {
            $('#Eid').val('');
        })
    </script>
}

Edit View :

@model WebApplication2.Models.EMPVM3

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




<div class="row">
    <form class="form-horizontal">
        <div class="form-group">
            <label class="control-label col-lg-4" asp-for="DEPT.Did"></label>
            <div class="col-lg-4">
                <input class="form-control" asp-for="DEPT.Did" />
            </div>
        </div>
        <div class="form-group">
            <label class="control-label col-lg-4" asp-for="DEPT.Dname"></label>
            <div class="col-lg-4">
                <input class="form-control" asp-for="DEPT.Dname" />
            </div>
        </div>
        <div class="form-group">
            <label class="control-label col-lg-4"></label>
            <div class="col-lg-4">
                <table width="100%" cellpadding="1" cellspacing="1">
                    <tr><th>EID</th><th>NAME</th><th></th></tr>
                    @{


                        <tr><td><input class="form-control" asp-for="EMP.Eid" id="Eid" /></td><td><input class="form-control" asp-for="EMP.Name" /></td><td><input type="submit" asp-action="Add" asp-controller="JBS" value="Add" name="Add" style="width:80px" class="btn btn-primary" /></td></tr>

                        if (Model.LEMP.Count != 0)
                        {
                            for (int i = 0; i < Model.LEMP.Count; i++)
                            {
                                <tr><td><input class="form-control" asp-for="@Model.LEMP[i].Eid" /></td><td><input class="form-control" asp-for="@Model.LEMP[i].Name" /></td><td><input asp-action="Remove" asp-controller="JBS" asp-route-id="@Model.LEMP[i].Eid" value="Remove" type="submit" style="width:80px" name="Remove" class="btn btn-primary" /></td></tr>
                            }
                        }
                    }
                </table>
            </div>
        </div>
        <div class="form-group">
            <label class="control-label col-lg-4"></label>
            <div class="col-lg-4">
                <input type="submit" value="Save" style="width:80px" name="Save" asp-action="Update" asp-controller="JBS" class="btn btn-primary" />
            </div>
        </div>
    </form>
</div>

<div>
    <a asp-action="Index">Back to List</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
    <script type="text/javascript">
        $(function () {
            $('#Eid').val('');
        })
    </script>
}





No comments:

Post a Comment