Dot net core :
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication5.Models
{
public class COUNTRY
{
[Key]
public int CID { get; set; }
[MaxLength(50)]
public string CNAME { get; set; }
}
}
--
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication5.Models
{
public class STATE
{
[Key]
public int SID { get; set; }
[MaxLength(50)]
public string SNAME { get; set; }
public int CID { get; set; }
}
}
--
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication5.Models
{
public class HOBBY
{
[Key]
public int HID { get; set; }
[MaxLength(50)]
public string HNAME { get; set; }
}
}
--
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication5.Models
{
public class INTERESET
{
[Key]
public int IID { get; set; }
[MaxLength(50)]
public string INAME { get; set; }
}
}
--
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication5.Models
{
public class EMP
{
[Key]
public int EID { get; set; }
[MaxLength(50)]
public string NAME { get; set; }
public string ADDRESS { get; set; }
[MaxLength(50)]
public string PASSWORD { get; set; }
[MaxLength(50)]
public string EMAIL { get; set; }
public Decimal SALARY { get; set; }
public DateTime DOB { get; set; }
[MaxLength(50)]
public string GENDER { get; set; }
public string PATH { get; set; }
public int CID { get; set; }
public int SID { get; set; }
}
}
--
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication5.Models
{
public class HMAP
{
[Key]
public int ID { get; set; }
public int EID { get; set; }
public int HID { get; set; }
}
}
--
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication5.Models
{
public class IMAP
{
[Key]
public int ID { get; set; }
public int EID { get; set; }
public int IID { get; set; }
}
}
--
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication5.Models
{
public class EMPVM
{
public EMPVM()
{
INTEREST = new List<SelectListItem>();
LCOUNTRY = new List<SelectListItem>();
LSTATE = new List<SelectListItem>();
LHOBBY = new List<SelectListItem>();
HOBBY = new List<string>();
}
public int EID { get; set; }
[Required(ErrorMessage ="Name should not be blank.")]
public string NAME { get; set; }
[Required(ErrorMessage = "Name should not be blank.")]
[DataType(DataType.MultilineText)]
public string ADDRESS { get; set; }
[Required(ErrorMessage = "Password should not be blank.")]
[StringLength(8, MinimumLength = 6, ErrorMessage = "Password length between 6 to 8 charecters long.")]
[DataType(DataType.Password)]
public string PASSWORD { get; set; }
[Required(ErrorMessage = "Confirm password should not be blank.")]
[DataType(DataType.Password)]
[Display(Name ="CONFIRM PASSWORD")]
[Compare("PASSWORD",ErrorMessage ="Password and confirm passwod must be same.")]
public string CPASSWORD { get; set; }
[Required(ErrorMessage = "Email id should not be blank.")]
[RegularExpression(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", ErrorMessage ="Invalid mail id.")]
[Remote("Check","Emp",ErrorMessage = "This mail id is already exists")]
public string EMAIL { get; set; }
[Required(ErrorMessage = "Salary should not be blank.")]
[Range(5000,500000,ErrorMessage ="Salary range between 5000 to 500000.")]
public Decimal? SALARY { get; set; }
[Required(ErrorMessage = "DOB should not be blank.")]
public DateTime DOB { get; set; }
[Required(ErrorMessage = "Please select a gender.")]
public string GENDER { get; set; }
[Customvalidation(ErrorMessage ="Please select a interest.")]
public List<SelectListItem> INTEREST { get; set; }
[Required(ErrorMessage = "Please select a country.")]
public int COUNTRY { get; set; }
public List<SelectListItem> LCOUNTRY { get; set; }
[Required(ErrorMessage = "Please select a state.")]
public int STATE { get; set; }
public List<SelectListItem> LSTATE { get; set; }
[Required(ErrorMessage = "Please select a hobby.")]
public List<string> HOBBY { get; set; }
public List<SelectListItem> LHOBBY { get; set; }
[Required(ErrorMessage = "Please select a photo.")]
public IFormFile PHOTO { get; set; }
public string PATH { get; set; }
public void Fillddl(List<SelectListItem> lcountry, List<SelectListItem> lhobby, List<SelectListItem> linterest, List<SelectListItem> lstate=null)
{
LCOUNTRY = lcountry;
LHOBBY = lhobby;
INTEREST = linterest;
LSTATE = lstate;
}
}
}
public class Customvalidation: ValidationAttribute
{
public override bool IsValid(object value)
{
if (value == null)
return false;
else
return (((List<SelectListItem>)value).Count(m => m.Selected == true) > 0);
}
}
--
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication5.Models
{
public class AppDbContext :DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options):base(options)
{
}
public DbSet<COUNTRY> Countries { get; set; }
public DbSet<STATE> States { get; set; }
public DbSet<HOBBY> Hobbies { get; set; }
public DbSet<INTERESET> Interesets { get; set; }
public DbSet<EMP> Emps { get; set; }
public DbSet<HMAP> Hmaps { get; set; }
public DbSet<IMAP> Imaps { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<COUNTRY>().HasData(new COUNTRY() { CID=1,CNAME="X"},new COUNTRY() { CID = 2, CNAME = "Y" },new COUNTRY() { CID = 3, CNAME = "Z" });
modelBuilder.Entity<STATE>().HasData(new STATE { SID = 1, SNAME = "A", CID = 1 }, new STATE { SID = 2, SNAME = "B", CID = 1 }, new STATE { SID = 3, SNAME = "C", CID = 2 }, new STATE { SID = 4, SNAME = "D", CID = 2 }, new STATE { SID = 5, SNAME = "E", CID = 3 }, new STATE { SID = 6, SNAME = "F", CID = 3 });
modelBuilder.Entity<HOBBY>().HasData(new HOBBY { HID = 1, HNAME = "Reading" }, new HOBBY { HID = 2, HNAME = "Writing" }, new HOBBY { HID = 3, HNAME = "Singing" }, new HOBBY { HID = 4, HNAME = "Playing" });
modelBuilder.Entity<INTERESET>().HasData(new INTERESET { IID = 1, INAME = "Cricket" }, new INTERESET { IID = 2, INAME = "Football" }, new INTERESET { IID = 3, INAME = "Baseball" }, new INTERESET { IID = 4, INAME = "Hockey" });
}
}
}
--
Install the following 2 NuGet packages.
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Tools
--
Add connection string in appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"DbConnection": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=DBTest789;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"
}
}
--
Call the connection in Startup class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using WebApplication5.Models;
namespace WebApplication5
{
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.AddDbContextPool<AppDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DbConnection")));
services.AddScoped<IDalRepository, DalRepository>();
}
// 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");
}
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 WebApplication5.Models
{
public interface IDalRepository
{
Task<IEnumerable<EMP>> Gete();
Task<IEnumerable<COUNTRY>> Getc();
Task<IEnumerable<STATE>> Gets(int CID);
Task<IEnumerable<HOBBY>> Geth();
Task<IEnumerable<INTERESET>> Geti();
Task<IEnumerable<HMAP>> Gethm();
Task<IEnumerable<IMAP>> Getim();
Task<EMP> Get(int EID);
Task<EMP> Save(EMPVM eMPVM);
Task<EMP> Update(EMPVM eMPVM);
Task<EMP> Delete(int EID);
}
}
--
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace WebApplication5.Models
{
public class DalRepository : IDalRepository
{
private readonly AppDbContext dbContext;
public DalRepository(AppDbContext DbContext)
{
this.dbContext = DbContext;
}
public async Task<EMP> Delete(int EID)
{
EMP emp = await dbContext.Emps.FindAsync(EID);
dbContext.Entry(emp).State = EntityState.Deleted;
dbContext.Hmaps.RemoveRange(dbContext.Hmaps.Where(m => m.EID == EID));
dbContext.Imaps.RemoveRange(dbContext.Imaps.Where(m => m.EID == EID));
await dbContext.SaveChangesAsync();
return emp;
}
public async Task<IEnumerable<COUNTRY>> Getc()
{
return await dbContext.Countries.ToListAsync();
}
public async Task<IEnumerable<EMP>> Gete()
{
return await dbContext.Emps.ToListAsync();
}
public async Task<EMP> Get(int EID)
{
return await dbContext.Emps.FirstOrDefaultAsync(m => m.EID == EID);
}
public async Task<IEnumerable<HOBBY>> Geth()
{
return await dbContext.Hobbies.ToListAsync();
}
public async Task<IEnumerable<HMAP>> Gethm()
{
return await dbContext.Hmaps.ToListAsync();
}
public async Task<IEnumerable<INTERESET>> Geti()
{
return await dbContext.Interesets.ToListAsync();
}
public async Task<IEnumerable<IMAP>> Getim()
{
return await dbContext.Imaps.ToListAsync();
}
public async Task<IEnumerable<STATE>> Gets(int CID)
{
return await dbContext.States.Where(m => m.CID == CID).ToListAsync();
}
public async Task<EMP> Save(EMPVM eMPVM)
{
EMP emp = new EMP
{
NAME = eMPVM.NAME,
ADDRESS = eMPVM.ADDRESS,
PASSWORD = eMPVM.PASSWORD,
EMAIL = eMPVM.EMAIL,
SALARY = eMPVM.SALARY.Value,
DOB = eMPVM.DOB,
GENDER = eMPVM.GENDER,
CID = eMPVM.COUNTRY,
SID = eMPVM.STATE,
PATH = eMPVM.PATH,
};
dbContext.Entry(emp).State = EntityState.Added;
await dbContext.SaveChangesAsync();
await dbContext.Hmaps.AddRangeAsync(eMPVM.HOBBY.Select(m => new HMAP { EID = emp.EID, HID = Convert.ToInt32(m) }));
await dbContext.Imaps.AddRangeAsync(eMPVM.INTEREST.Where(n => n.Selected == true).Select(m => new IMAP { EID = emp.EID, IID = Convert.ToInt32(m.Value)}));
await dbContext.SaveChangesAsync();
return emp;
}
public async Task<EMP> Update(EMPVM eMPVM)
{
EMP emp = await dbContext.Emps.FindAsync(eMPVM.EID);
emp.NAME = eMPVM.NAME;
emp.ADDRESS = eMPVM.ADDRESS;
emp.PASSWORD = eMPVM.PASSWORD;
emp.EMAIL = eMPVM.EMAIL;
emp.SALARY = eMPVM.SALARY.Value;
emp.DOB = eMPVM.DOB;
emp.GENDER = eMPVM.GENDER;
emp.CID = eMPVM.COUNTRY;
emp.SID = eMPVM.STATE;
if(eMPVM.PATH!=null)
emp.PATH = eMPVM.PATH;
dbContext.Entry(emp).State = EntityState.Modified;
dbContext.Hmaps.RemoveRange(dbContext.Hmaps.Where(m => m.EID == eMPVM.EID));
dbContext.Imaps.RemoveRange(dbContext.Imaps.Where(m => m.EID == eMPVM.EID));
await dbContext.Hmaps.AddRangeAsync(eMPVM.HOBBY.Select(m => new HMAP { EID = emp.EID, HID = Convert.ToInt32(m) }));
await dbContext.Imaps.AddRangeAsync(eMPVM.INTEREST.Where(n => n.Selected == true).Select(m => new IMAP { EID = emp.EID, IID = Convert.ToInt32(m.Value) }));
await dbContext.SaveChangesAsync();
return emp;
}
}
}
--
Create and execute database migrations
Use the following 2 commands to create and execute the initial database migration
Add-Migration <Migration Name>
Update-Database
below commands for removing migration
Update-Database <Migration Name>
remove-migration
--
Create and execute database migrations
Use the following 2 commands to create and execute the initial database migration
Add-Migration <Migration Name>
Update-Database
below commands for removing migration
Update-Database <Migration Name>
remove-migration
--
MVC Controller :
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using WebApplication5.Models;
using Microsoft.AspNetCore.Hosting;
namespace WebApplication5.Controllers
{
public class EmpController : Controller
{
#region Declaretion
private readonly IDalRepository dal;
private readonly IHostingEnvironment hostingEnvironment;
#endregion
public EmpController(IDalRepository Dal, IHostingEnvironment HostingEnvironment)
{
this.dal = Dal;
this.hostingEnvironment = HostingEnvironment;
}
[HttpGet]
public async Task<IActionResult> Index()
{
return View(await dal.Gete());
}
[HttpGet]
public async Task<IActionResult> Create()
{
EMPVM eMPVM = new EMPVM();
var Lcountry = await dal.Getc();
eMPVM.Fillddl(Lcountry.Select(m => new SelectListItem { Value = m.CID.ToString(), Text = m.CNAME }).ToList(), dal.Geth().Result.Select(m => new SelectListItem { Value = m.HID.ToString(), Text = m.HNAME }).ToList(), dal.Geti().Result.Select(m => new SelectListItem { Value = m.IID.ToString(), Text = m.INAME }).ToList());
return View(eMPVM);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(EMPVM eMPVM)
{
if (ModelState.IsValid)
{
string uniqueFileName = null;
string filePath = null;
string uploadsFolder = string.Empty;
if (eMPVM.PHOTO != null)
{
uploadsFolder = Path.Combine(hostingEnvironment.WebRootPath, "Images");
uniqueFileName = Guid.NewGuid().ToString() + "_" + eMPVM.PHOTO.FileName.Substring(3);
filePath = Path.Combine(uploadsFolder, uniqueFileName);
eMPVM.PHOTO.CopyTo(new FileStream(filePath, FileMode.Create));
}
eMPVM.PATH = uniqueFileName;
EMP emp = await dal.Save(eMPVM);
return RedirectToAction("Index");
}
eMPVM.Fillddl(dal.Getc().Result.Select(m => new SelectListItem { Value = m.CID.ToString(), Text = m.CNAME }).ToList(), dal.Geth().Result.Select(m => new SelectListItem { Value = m.HID.ToString(), Text = m.HNAME }).ToList(), dal.Geti().Result.Select(m => new SelectListItem { Value = m.IID.ToString(), Text = m.INAME }).ToList());
return View(eMPVM);
}
[HttpGet]
public async Task<IActionResult> Edit(int id)
{
EMP emp = await dal.Get(id);
EMPVM eMPVM = new EMPVM()
{
EID = emp.EID,
NAME = emp.NAME,
ADDRESS = emp.ADDRESS,
DOB = emp.DOB,
EMAIL = emp.EMAIL,
GENDER = emp.GENDER,
COUNTRY = emp.CID,
STATE = emp.SID,
PATH = emp.PATH,
HOBBY = dal.Gethm().Result.Where(m => m.EID == id).Select(n => n.HID.ToString()).ToList(),
SALARY = emp.SALARY,
};
var data = (from x in dal.Geti().Result
join y in dal.Getim().Result.Where(x => x.EID == id)
on x.IID equals y.IID
select new SelectListItem { Value = x.IID.ToString(), Text = x.INAME, Selected = true }).ToList();
var data1 = dal.Geti().Result.Select(x => new { x.IID, x.INAME }).Except(data.Select(y => new { IID = Convert.ToInt32(y.Value), INAME = y.Text })).Select(z => new SelectListItem { Value = z.IID.ToString(), Text = z.INAME, Selected = false }).ToList();
var data3 = data.Union(data1);
var Lcountry = await dal.Getc();
eMPVM.Fillddl(Lcountry.Select(m => new SelectListItem { Value = m.CID.ToString(), Text = m.CNAME }).ToList(), dal.Geth().Result.Select(m => new SelectListItem { Value = m.HID.ToString(), Text = m.HNAME }).ToList(), data3.ToList(), dal.Gets(eMPVM.COUNTRY).Result.Select(m => new SelectListItem { Value = m.SID.ToString(), Text = m.SNAME }).ToList());
return View(eMPVM);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(EMPVM eMPVM)
{
ModelState.Remove("PASSWORD");
ModelState.Remove("CPASSWORD");
ModelState.Remove("PHOTO");
if (ModelState.IsValid)
{
string uniqueFileName = null;
string filePath = null;
string uploadsFolder = string.Empty;
if (eMPVM.PHOTO != null)
{
uploadsFolder = Path.Combine(hostingEnvironment.WebRootPath, "Images");
uniqueFileName = Guid.NewGuid().ToString() + "_" + eMPVM.PHOTO.FileName.Substring(3);
filePath = Path.Combine(uploadsFolder, uniqueFileName);
eMPVM.PHOTO.CopyTo(new FileStream(filePath, FileMode.Create));
eMPVM.PATH = uniqueFileName;
}
EMP emp = await dal.Update(eMPVM);
return RedirectToAction("Index");
}
eMPVM.Fillddl(dal.Getc().Result.Select(m => new SelectListItem { Value = m.CID.ToString(), Text = m.CNAME }).ToList(), dal.Geth().Result.Select(m => new SelectListItem { Value = m.HID.ToString(), Text = m.HNAME }).ToList(), dal.Geti().Result.Select(m => new SelectListItem { Value = m.IID.ToString(), Text = m.INAME }).ToList());
return View(eMPVM);
}
[HttpGet]
public async Task<IActionResult> Delete(int id)
{
EMP emp = await dal.Get(id);
EMPVM eMPVM = new EMPVM()
{
EID = emp.EID,
NAME = emp.NAME,
GENDER = emp.GENDER
};
return View(eMPVM);
}
[HttpPost]
public async Task<IActionResult> Delete(EMPVM eMPVM)
{
EMP emp = await dal.Delete(eMPVM.EID);
return RedirectToAction("Index");
}
[HttpGet]
public async Task<JsonResult> Fill(int CID)
{
return Json(await dal.Gets(CID));
}
[HttpGet]
public async Task<JsonResult> Check(string EMAIL)
{
var data = await dal.Gete();
return Json(!data.Any(p => p.EMAIL.Trim().ToLower() == EMAIL.Trim().ToLower()));
}
}
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using WebApplication5.Models;
using Microsoft.AspNetCore.Hosting;
namespace WebApplication5.Controllers
{
public class EmpController : Controller
{
#region Declaretion
private readonly IDalRepository dal;
private readonly IHostingEnvironment hostingEnvironment;
#endregion
public EmpController(IDalRepository Dal, IHostingEnvironment HostingEnvironment)
{
this.dal = Dal;
this.hostingEnvironment = HostingEnvironment;
}
[HttpGet]
public async Task<IActionResult> Index()
{
return View(await dal.Gete());
}
[HttpGet]
public async Task<IActionResult> Create()
{
EMPVM eMPVM = new EMPVM();
var Lcountry = await dal.Getc();
eMPVM.Fillddl(Lcountry.Select(m => new SelectListItem { Value = m.CID.ToString(), Text = m.CNAME }).ToList(), dal.Geth().Result.Select(m => new SelectListItem { Value = m.HID.ToString(), Text = m.HNAME }).ToList(), dal.Geti().Result.Select(m => new SelectListItem { Value = m.IID.ToString(), Text = m.INAME }).ToList());
return View(eMPVM);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(EMPVM eMPVM)
{
if (ModelState.IsValid)
{
string uniqueFileName = null;
string filePath = null;
string uploadsFolder = string.Empty;
if (eMPVM.PHOTO != null)
{
uploadsFolder = Path.Combine(hostingEnvironment.WebRootPath, "Images");
uniqueFileName = Guid.NewGuid().ToString() + "_" + eMPVM.PHOTO.FileName.Substring(3);
filePath = Path.Combine(uploadsFolder, uniqueFileName);
eMPVM.PHOTO.CopyTo(new FileStream(filePath, FileMode.Create));
}
eMPVM.PATH = uniqueFileName;
EMP emp = await dal.Save(eMPVM);
return RedirectToAction("Index");
}
eMPVM.Fillddl(dal.Getc().Result.Select(m => new SelectListItem { Value = m.CID.ToString(), Text = m.CNAME }).ToList(), dal.Geth().Result.Select(m => new SelectListItem { Value = m.HID.ToString(), Text = m.HNAME }).ToList(), dal.Geti().Result.Select(m => new SelectListItem { Value = m.IID.ToString(), Text = m.INAME }).ToList());
return View(eMPVM);
}
[HttpGet]
public async Task<IActionResult> Edit(int id)
{
EMP emp = await dal.Get(id);
EMPVM eMPVM = new EMPVM()
{
EID = emp.EID,
NAME = emp.NAME,
ADDRESS = emp.ADDRESS,
DOB = emp.DOB,
EMAIL = emp.EMAIL,
GENDER = emp.GENDER,
COUNTRY = emp.CID,
STATE = emp.SID,
PATH = emp.PATH,
HOBBY = dal.Gethm().Result.Where(m => m.EID == id).Select(n => n.HID.ToString()).ToList(),
SALARY = emp.SALARY,
};
var data = (from x in dal.Geti().Result
join y in dal.Getim().Result.Where(x => x.EID == id)
on x.IID equals y.IID
select new SelectListItem { Value = x.IID.ToString(), Text = x.INAME, Selected = true }).ToList();
var data1 = dal.Geti().Result.Select(x => new { x.IID, x.INAME }).Except(data.Select(y => new { IID = Convert.ToInt32(y.Value), INAME = y.Text })).Select(z => new SelectListItem { Value = z.IID.ToString(), Text = z.INAME, Selected = false }).ToList();
var data3 = data.Union(data1);
var Lcountry = await dal.Getc();
eMPVM.Fillddl(Lcountry.Select(m => new SelectListItem { Value = m.CID.ToString(), Text = m.CNAME }).ToList(), dal.Geth().Result.Select(m => new SelectListItem { Value = m.HID.ToString(), Text = m.HNAME }).ToList(), data3.ToList(), dal.Gets(eMPVM.COUNTRY).Result.Select(m => new SelectListItem { Value = m.SID.ToString(), Text = m.SNAME }).ToList());
return View(eMPVM);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(EMPVM eMPVM)
{
ModelState.Remove("PASSWORD");
ModelState.Remove("CPASSWORD");
ModelState.Remove("PHOTO");
if (ModelState.IsValid)
{
string uniqueFileName = null;
string filePath = null;
string uploadsFolder = string.Empty;
if (eMPVM.PHOTO != null)
{
uploadsFolder = Path.Combine(hostingEnvironment.WebRootPath, "Images");
uniqueFileName = Guid.NewGuid().ToString() + "_" + eMPVM.PHOTO.FileName.Substring(3);
filePath = Path.Combine(uploadsFolder, uniqueFileName);
eMPVM.PHOTO.CopyTo(new FileStream(filePath, FileMode.Create));
eMPVM.PATH = uniqueFileName;
}
EMP emp = await dal.Update(eMPVM);
return RedirectToAction("Index");
}
eMPVM.Fillddl(dal.Getc().Result.Select(m => new SelectListItem { Value = m.CID.ToString(), Text = m.CNAME }).ToList(), dal.Geth().Result.Select(m => new SelectListItem { Value = m.HID.ToString(), Text = m.HNAME }).ToList(), dal.Geti().Result.Select(m => new SelectListItem { Value = m.IID.ToString(), Text = m.INAME }).ToList());
return View(eMPVM);
}
[HttpGet]
public async Task<IActionResult> Delete(int id)
{
EMP emp = await dal.Get(id);
EMPVM eMPVM = new EMPVM()
{
EID = emp.EID,
NAME = emp.NAME,
GENDER = emp.GENDER
};
return View(eMPVM);
}
[HttpPost]
public async Task<IActionResult> Delete(EMPVM eMPVM)
{
EMP emp = await dal.Delete(eMPVM.EID);
return RedirectToAction("Index");
}
[HttpGet]
public async Task<JsonResult> Fill(int CID)
{
return Json(await dal.Gets(CID));
}
[HttpGet]
public async Task<JsonResult> Check(string EMAIL)
{
var data = await dal.Gete();
return Json(!data.Any(p => p.EMAIL.Trim().ToLower() == EMAIL.Trim().ToLower()));
}
}
}
Index View :
@model IEnumerable<WebApplication5.Models.EMP>
@{
ViewData["Title"] = "Index";
}
<p>
<a asp-action="Create" class="btn btn-primary">Add New</a>
</p>
<table class="table table-bordered table-hover table-striped">
<thead class="bg bg-primary">
<tr>
<th>
@Html.DisplayNameFor(model => model.NAME)
</th>
<th>
@Html.DisplayNameFor(model => model.ADDRESS)
</th>
<th>
@Html.DisplayNameFor(model => model.EMAIL)
</th>
<th>
@Html.DisplayNameFor(model => model.SALARY)
</th>
<th>
@Html.DisplayNameFor(model => model.DOB)
</th>
<th>
@Html.DisplayNameFor(model => model.GENDER)
</th>
<th>
PHOTO
</th>
<th>ACTION</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.NAME)
</td>
<td>
@Html.DisplayFor(modelItem => item.ADDRESS)
</td>
<td>
@Html.DisplayFor(modelItem => item.EMAIL)
</td>
<td>
@Html.DisplayFor(modelItem => item.SALARY)
</td>
<td>
@{
string s = string.Format("{0:dd-MMM-yy}", item.DOB);
}
@s
</td>
<td>
@Html.DisplayFor(modelItem => item.GENDER)
</td>
<td>
@{
string t = "~/images/" + item.PATH;
}
<img height="50" width="50" src="@t" asp-append-version="true" />
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.EID }) |
@Html.ActionLink("Delete", "Delete", new { id=item.EID })
</td>
</tr>
}
</tbody>
</table>
Create View :
@model WebApplication5.Models.EMPVM
@{
ViewData["Title"] = "Create";
}
<div class="row">
<div class="col-md-4">
<form asp-action="Create" enctype="multipart/form-data" method="post" asp-antiforgery="true">
<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" />
<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">
<label asp-for="PASSWORD" class="control-label"></label>
<input asp-for="PASSWORD" class="form-control" />
<span asp-validation-for="PASSWORD" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="CPASSWORD" class="control-label"></label>
<input asp-for="CPASSWORD" class="form-control" />
<span asp-validation-for="CPASSWORD" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="EMAIL" class="control-label"></label>
<input asp-for="EMAIL" class="form-control" />
<span asp-validation-for="EMAIL" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="SALARY" class="control-label"></label>
<input asp-for="SALARY" class="form-control" />
<span asp-validation-for="SALARY" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="DOB" class="control-label"></label>
<input asp-for="DOB" class="form-control" autocomplete="off" />
<span asp-validation-for="DOB" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="GENDER" class="control-label"></label><br />
<input type="radio" asp-for="GENDER" value="Male" />Male
<input type="radio" asp-for="GENDER" value="Female" />Female
<span asp-validation-for="GENDER" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="INTEREST" class="control-label"></label><br />
@{
for (int i = 0; i < Model.INTEREST.Count; i++)
{
<fieldset>
<legend></legend>
<input type="hidden" asp-for="@Model.INTEREST[i].Value" />
<input type="hidden" asp-for="@Model.INTEREST[i].Value" />
<input type="checkbox" asp-for="@Model.INTEREST[i].Selected" /> @Model.INTEREST[i].Text
</fieldset>
}
}
<span asp-validation-for="INTEREST" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="COUNTRY" class="control-label"></label>
<select asp-for="COUNTRY" class="form-control" asp-items="Model.LCOUNTRY">
<option value="">Select</option>
</select>
<span asp-validation-for="COUNTRY" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="STATE" class="control-label"></label>
<select asp-for="STATE" class="form-control" asp-items="Model.LSTATE">
<option value="">Select</option>
</select>
<span asp-validation-for="STATE" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="HOBBY" class="control-label"></label>
<select asp-for="HOBBY" class="form-control" multiple asp-items="Model.LHOBBY" style="width:350px">
</select>
<span asp-validation-for="HOBBY" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="PHOTO" class="control-label"></label>
<input asp-for="PHOTO" class="form-control" type="file" />
<span asp-validation-for="PHOTO" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script type="text/javascript">
$(function () {
$('#DOB').attr("type", "");
$('#DOB').datepicker({
dateFormat: 'dd-mm-yy'
});
$('#SALARY').val('');
$('#HOBBY').multiselect();
$('#COUNTRY').change(function () {
$('#STATE').empty();
$('#STATE').append("<option>Select</option>");
$.ajax({
url: '@Url.Action("Fill","Emp")',
type: 'Get',
dataType: 'Json',
contentType: 'application/json; charset=utf-8',
data: { CID: $(this).val() },
success: function (data) {
$.each(data, function (i,v) {
$('#STATE').append("<option value='"+v.SID+"'>"+v.SNAME+"</option>");
})
}
});
})
});
</script>
}
Edit View :
@model WebApplication5.Models.EMPVM
@{
ViewData["Title"] = "Edit";
}
<div class="row">
<div class="col-md-4">
<form asp-action="Edit" enctype="multipart/form-data" method="post" asp-antiforgery="true">
<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 type="hidden" asp-for="EID" />
<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">
<label asp-for="EMAIL" class="control-label"></label>
<input asp-for="EMAIL" class="form-control" />
<span asp-validation-for="EMAIL" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="SALARY" class="control-label"></label>
<input asp-for="SALARY" class="form-control" />
<span asp-validation-for="SALARY" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="DOB" class="control-label"></label>
<input asp-for="DOB" class="form-control" autocomplete="off" />
<span asp-validation-for="DOB" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="GENDER" class="control-label"></label><br />
<input type="radio" asp-for="GENDER" value="Male" />Male
<input type="radio" asp-for="GENDER" value="Female" />Female
<span asp-validation-for="GENDER" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="INTEREST" class="control-label"></label><br />
@{
for (int i = 0; i < Model.INTEREST.Count; i++)
{
<fieldset>
<legend></legend>
<input type="hidden" asp-for="@Model.INTEREST[i].Value" />
<input type="hidden" asp-for="@Model.INTEREST[i].Value" />
<input type="checkbox" asp-for="@Model.INTEREST[i].Selected" /> @Model.INTEREST[i].Text
</fieldset>
}
}
<span asp-validation-for="INTEREST" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="COUNTRY" class="control-label"></label>
<select asp-for="COUNTRY" class="form-control" asp-items="Model.LCOUNTRY">
<option value="">Select</option>
</select>
<span asp-validation-for="COUNTRY" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="STATE" class="control-label"></label>
<select asp-for="STATE" class="form-control" asp-items="Model.LSTATE">
<option value="">Select</option>
</select>
<span asp-validation-for="STATE" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="HOBBY" class="control-label"></label>
<select asp-for="HOBBY" class="form-control" multiple asp-items="Model.LHOBBY" style="width:350px">
</select>
<span asp-validation-for="HOBBY" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="PHOTO" class="control-label"></label>
<input asp-for="PHOTO" class="form-control" type="file" />
<span asp-validation-for="PHOTO" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script type="text/javascript">
$(function () {
$("#PASSWORD").rules("remove", "required")
$("#CPASSWORD").rules("remove", "required")
$("#PHOTO").rules("remove", "required")
$("#EMAIL").rules("remove", "remote")
$('#DOB').attr("type", "");
$('#DOB').datepicker({
dateFormat: 'dd-mm-yy'
});
$('#HOBBY').multiselect();
$('#COUNTRY').change(function () {
$('#STATE').empty();
$('#STATE').append("<option>Select</option>");
$.ajax({
url: '@Url.Action("Fill","Emp")',
type: 'Get',
dataType: 'Json',
contentType: 'application/json; charset=utf-8',
data: { CID: $(this).val() },
success: function (data) {
$.each(data, function (i,v) {
$('#STATE').append("<option value='"+v.SID+"'>"+v.SNAME+"</option>");
})
}
});
})
});
</script>
}
Layout Page :
@model WebApplication5.Models.EMPVM
@{
ViewData["Title"] = "Edit";
}
<div class="row">
<div class="col-md-4">
<form asp-action="Edit" enctype="multipart/form-data" method="post" asp-antiforgery="true">
<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 type="hidden" asp-for="EID" />
<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">
<label asp-for="EMAIL" class="control-label"></label>
<input asp-for="EMAIL" class="form-control" />
<span asp-validation-for="EMAIL" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="SALARY" class="control-label"></label>
<input asp-for="SALARY" class="form-control" />
<span asp-validation-for="SALARY" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="DOB" class="control-label"></label>
<input asp-for="DOB" class="form-control" autocomplete="off" />
<span asp-validation-for="DOB" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="GENDER" class="control-label"></label><br />
<input type="radio" asp-for="GENDER" value="Male" />Male
<input type="radio" asp-for="GENDER" value="Female" />Female
<span asp-validation-for="GENDER" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="INTEREST" class="control-label"></label><br />
@{
for (int i = 0; i < Model.INTEREST.Count; i++)
{
<fieldset>
<legend></legend>
<input type="hidden" asp-for="@Model.INTEREST[i].Value" />
<input type="hidden" asp-for="@Model.INTEREST[i].Value" />
<input type="checkbox" asp-for="@Model.INTEREST[i].Selected" /> @Model.INTEREST[i].Text
</fieldset>
}
}
<span asp-validation-for="INTEREST" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="COUNTRY" class="control-label"></label>
<select asp-for="COUNTRY" class="form-control" asp-items="Model.LCOUNTRY">
<option value="">Select</option>
</select>
<span asp-validation-for="COUNTRY" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="STATE" class="control-label"></label>
<select asp-for="STATE" class="form-control" asp-items="Model.LSTATE">
<option value="">Select</option>
</select>
<span asp-validation-for="STATE" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="HOBBY" class="control-label"></label>
<select asp-for="HOBBY" class="form-control" multiple asp-items="Model.LHOBBY" style="width:350px">
</select>
<span asp-validation-for="HOBBY" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="PHOTO" class="control-label"></label>
<input asp-for="PHOTO" class="form-control" type="file" />
<span asp-validation-for="PHOTO" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script type="text/javascript">
$(function () {
$("#PASSWORD").rules("remove", "required")
$("#CPASSWORD").rules("remove", "required")
$("#PHOTO").rules("remove", "required")
$("#EMAIL").rules("remove", "remote")
$('#DOB').attr("type", "");
$('#DOB').datepicker({
dateFormat: 'dd-mm-yy'
});
$('#HOBBY').multiselect();
$('#COUNTRY').change(function () {
$('#STATE').empty();
$('#STATE').append("<option>Select</option>");
$.ajax({
url: '@Url.Action("Fill","Emp")',
type: 'Get',
dataType: 'Json',
contentType: 'application/json; charset=utf-8',
data: { CID: $(this).val() },
success: function (data) {
$.each(data, function (i,v) {
$('#STATE').append("<option value='"+v.SID+"'>"+v.SNAME+"</option>");
})
}
});
})
});
</script>
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - WebApplication5</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link href="~/lib/jqueryui/jquery-ui.min.css" rel="stylesheet" />
<link href="~/lib/multiselect/jquery.multiselect.css" rel="stylesheet" />
<link rel="stylesheet" href="~/css/site.css" />
</head>
<body>
<header>
<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
<div class="container">
<a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">WebApplication5</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent"
aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="navbar-collapse collapse d-sm-inline-flex flex-sm-row-reverse">
<ul class="navbar-nav flex-grow-1">
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Emp" asp-action="Index">Employee</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div class="container">
<main role="main" class="pb-3">
@RenderBody()
</main>
</div>
<footer class="border-top footer text-muted">
<div class="container">
© 2020 - WebApplication5 - <a asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
</div>
</footer>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/jqueryui/jquery-ui.min.js"></script>
<script src="~/lib/multiselect/multiselect.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
@RenderSection("Scripts", required: false)
</body>
</html>
No comments:
Post a Comment