using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
namespace WebApplication6.DAL
{
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.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication6.DAL
{
public class State
{
[Key]
public int SID { get; set; }
[MaxLength(50)]
public string SNAME { get; set; }
public int CID { get; set; }
[ForeignKey("CID")]
public virtual Country Country { get; set; }
}
}
-
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication6.DAL
{
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.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication6.DAL
{
public class Hobbymap
{
[Key]
public int ID { get; set; }
public int EID { get; set; }
[ForeignKey("EID")]
public virtual EMP EMP { get; set; }
public int HID { get; set; }
[ForeignKey("HID")]
public virtual Hobby Hobby { get; set; }
}
}
-
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication6.DAL
{
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<Hobbymap> Hobbymaps { get; set; }
public DbSet<EMP> EMPs { get; set; }
public DbSet<DEPT> Depts { get; set; }
public DbSet<Test> Tests { get; set; }
public DbSet<Newemp> Newemps { get; set; }
public DbSet<Hobbym> Hobbyms { 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<Hobby>().HasData(new Hobby { HID = 1, HNAME = "Cricket" }, new Hobby { HID = 2, HNAME = "Football" }, new Hobby { HID = 3, HNAME = "Baseball" }, new Hobby { HID = 4, HNAME = "Hockey" });
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 });
}
}
}
-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication6.DAL
{
public interface IRepository<T> where T: class
{
Task<IEnumerable<T>> Gets();
Task<T> Get(int ID);
Task<T> Save(T t);
Task<string> Update(T t);
Task<string> Delete(int ID);
Task<string> SaveAll(List<T> lst);
Task<string> DeleteAll(List<T> lst);
}
}
-
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication6.DAL
{
public class Repository<T> : IRepository<T> where T : class
{
#region
private readonly AppDbContext Context;
#endregion
public Repository(AppDbContext context)
{
this.Context = context;
}
public async Task<string> Delete(int ID)
{
Context.Set<T>().Remove(await Context.Set<T>().FindAsync(ID));
await Context.SaveChangesAsync();
return "Data Deleted.";
}
public async Task<string> DeleteAll(List<T> lst)
{
Context.Set<T>().RemoveRange(lst);
await Context.SaveChangesAsync();
return "All Data Deleted.";
}
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)
{
Context.Set<T>().Add(t);
await Context.SaveChangesAsync();
return t;
}
public async Task<string> SaveAll(List<T> lst)
{
Context.Set<T>().AddRange(lst);
await Context.SaveChangesAsync();
return "All Data Saved.";
}
public async Task<string> Update(T t)
{
Context.Set<T>().Update(t);
await Context.SaveChangesAsync();
return "Data Updated.";
}
}
}
-
using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebApplication6.DAL;
namespace WebApplication6.Models
{
public class MappingProfile : Profile
{
public MappingProfile()
{
CreateMap<EMP, EMPVM>();
CreateMap<EMPVM, EMP>();
CreateMap<Newemp, NEWEMPVM>();
CreateMap<NEWEMPVM, Newemp>();
}
}
}
-
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication6.Models
{
public class NEWEMPVM
{
public NEWEMPVM()
{
HOBBY = new List<string>();
Lhobby = new List<SelectListItem>();
LCID = new List<SelectListItem>();
LSID = new List<SelectListItem>();
}
public int EID { get; set; }
[Required]
public string NAME { get; set; }
[Required]
[DataType(DataType.MultilineText)]
public string ADDRESS { get; set; }
[Required]
public string GENDER { get; set; }
[Required]
[EmailAddress]
public string EMAIL { get; set; }
[Required]
public Decimal? SALARY { get; set; }
[Required]
public DateTime? DOJ { get; set; }
[Required]
public List<string> HOBBY { get; set; }
public List<SelectListItem> Lhobby { get; set; }
[Required]
[Display(Name = "COUNTRY")]
public int CID { get; set; }
public List<SelectListItem> LCID { get; set; }
[Required]
[Display(Name = "STATE")]
public int SID { get; set; }
public List<SelectListItem> LSID { get; set; }
[Required(ErrorMessage ="Please select a photo.")]
public IFormFile PHOTO { get; set; }
public string PATH { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
[RegularExpression(@"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^\da-zA-Z]).{6,100}$", ErrorMessage = "Password contains
at least one number,one uppercase,one lowercase & one special charecter
.")]
public string Password
{ get; set; }
[RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$", ErrorMessage = "Invalid mobile number.")]
public string Mobile { get; set; }
[RegularExpression(@"^(\d{6,9})$",
ErrorMessage = "Zip code will only accept numeric digits with length 6
digit")]
[RegularExpression(@"\d{5}", ErrorMessage = "Zip code will only
accept numeric digits with length 5 digit")]
[RegularExpression(@"^[a-zA-Z]+$",
ErrorMessage = "Please enter letters only")]
public void fillddl(List<SelectListItem> cl, List<SelectListItem> hl, List<SelectListItem> sl = null)
{
LCID = cl;
Lhobby = hl;
LSID = sl;
}
}
}
-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using WebApplication6.DAL;
using WebApplication6.Models;
namespace WebApplication6
{
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.AddAutoMapper(typeof(MappingProfile));
services.AddDbContextPool<AppDbContext>(options => options.UseSqlServer(@"Data Source=(localdb)\MSSQLLocalDB;DataBase=Testdb0;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"));
services.AddScoped<IRepository<Country>, Repository<Country>>();
services.AddScoped<IRepository<State>, Repository<State>>();
services.AddScoped<IRepository<Hobby>, Repository<Hobby>>();
services.AddScoped<IRepository<Hobbymap>, Repository<Hobbymap>>();
services.AddScoped<IRepository<EMP>, Repository<EMP>>();
services.AddScoped<IRepository<Newemp>, Repository<Newemp>>();
services.AddScoped<IRepository<Hobbym>, Repository<Hobbym>>();
services.AddControllersWithViews()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.PropertyNamingPolicy = null;
//options.JsonSerializerOptions.Converters.Add(new WebApplication1.Models.LongToStringConverter());
});
}
// 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.IO;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using WebApplication6.DAL;
using WebApplication6.Models;
namespace WebApplication6.Controllers
{
public class NewEmpController : Controller
{
#region
private readonly IRepository<Country> ic;
private readonly IRepository<State> ist;
private readonly IRepository<Hobby> ih;
private readonly IRepository<Hobbym> ihm;
private readonly IRepository<Newemp> ie;
private readonly IMapper mapper;
private readonly IHostingEnvironment hostingEnvironment;
#endregion
public NewEmpController(IRepository<Country> ic, IRepository<State> ist,
IRepository<Hobby> ih, IRepository<Hobbym> ihm, IRepository<Newemp> ie, IMapper mapper, IHostingEnvironment hostingEnvironment)
{
this.ic = ic;
this.ist = ist;
this.ih = ih;
this.ihm = ihm;
this.ie = ie;
this.mapper = mapper;
this.hostingEnvironment = hostingEnvironment;
}
[HttpGet]
public async Task<IActionResult> Index()
{
var lst = await ie.Gets();
return View(lst.ToList());
}
[HttpGet]
public async Task<IActionResult> Create()
{
NEWEMPVM nEWEMPVM = new NEWEMPVM();
var data = await ic.Gets();
nEWEMPVM.fillddl(data.Select(x => new SelectListItem { Value = x.CID.ToString(), Text = x.CNAME }).ToList(), ih.Gets().Result.Select(n => new SelectListItem { Value = n.HID.ToString(), Text = n.HNAME }).ToList(), new List<SelectListItem>());
return View(nEWEMPVM);
}
[HttpGet]
public async Task<IActionResult> Fillddl(int CID)
{
var data = await ist.Gets();
return Json(data.Where(m => m.CID == CID).ToList());
}
[HttpGet]
public async Task<IActionResult> Edit(int id)
{
Newemp newemp = await ie.Get(id);
NEWEMPVM nEWEMPVM = new NEWEMPVM();
mapper.Map(newemp, nEWEMPVM);
var data = await ic.Gets();
nEWEMPVM.fillddl(data.Select(x => new SelectListItem { Value = x.CID.ToString(), Text = x.CNAME }).ToList(), ih.Gets().Result.Select(n => new SelectListItem { Value = n.HID.ToString(), Text = n.HNAME }).ToList(), ist.Gets().Result.Where(m => m.CID == nEWEMPVM.CID).Select(p => new SelectListItem { Value = p.SID.ToString(), Text = p.SNAME }).ToList());
var data1= await ihm.Gets();
nEWEMPVM.HOBBY = data1.Where(m => m.EID == id).Select(p => p.HID.ToString()).ToList();
return View("Create", nEWEMPVM);
}
[HttpPost]
public async Task<IActionResult> Create(NEWEMPVM nEWEMPVM)
{
Newemp emp = new Newemp();
mapper.Map(nEWEMPVM, emp);
if (nEWEMPVM.EID > 0)
ModelState.Remove("PHOTO");
if (ModelState.IsValid)
{
if (nEWEMPVM.PHOTO != null)
{
string uploadsFolder = Path.Combine(hostingEnvironment.WebRootPath, "Image");
string uniqueFileName = Guid.NewGuid().ToString() + "_" + nEWEMPVM.PHOTO.FileName.Substring(3);
string filePath = Path.Combine(uploadsFolder, nEWEMPVM.PHOTO.FileName);
nEWEMPVM.PHOTO.CopyTo(new FileStream(filePath, FileMode.Create));
emp.PATH = nEWEMPVM.PHOTO.FileName;
}
if (nEWEMPVM.EID < 1)
{
emp = await ie.Save(emp);
}
else
{
string t = await ie.Update(emp);
t = await ihm.DeleteAll(ihm.Gets().Result.Where(m => m.EID == nEWEMPVM.EID).ToList());
}
string s = await ihm.SaveAll(nEWEMPVM.HOBBY.Select(x => new Hobbym { EID = emp.EID, HID = Convert.ToInt32(x) }).ToList());
return RedirectToAction("Index");
}
else
{
var data = await ic.Gets();
nEWEMPVM.fillddl(data.Select(x => new SelectListItem { Value = x.CID.ToString(), Text = x.CNAME }).ToList(), ih.Gets().Result.Select(n => new SelectListItem { Value = n.HID.ToString(), Text = n.HNAME }).ToList(), ist.Gets().Result.Where(m => m.CID == nEWEMPVM.CID).Select(p => new SelectListItem { Value = p.SID.ToString(), Text = p.SNAME }).ToList());
return View(nEWEMPVM);
}
}
[HttpGet]
public async Task<IActionResult> Delete(int id)
{
await ie.Delete(id);
string t = await ihm.DeleteAll(ihm.Gets().Result.Where(m => m.EID == id).ToList());
return RedirectToAction("Index");
}
}
}
-
@model IEnumerable<WebApplication6.DAL.Newemp>
@{
ViewData["Title"] = "Index";
}
<p>
<a asp-action="Create" class="btn btn-primary">Add New</a>
</p>
<table class="table table-bordered table-hover" id="tb">
<thead class="bg-primary">
<tr>
<th>
@Html.DisplayNameFor(model => model.NAME)
</th>
<th>
@Html.DisplayNameFor(model => model.ADDRESS)
</th>
<th>
@Html.DisplayNameFor(model => model.GENDER)
</th>
<th>
@Html.DisplayNameFor(model => model.EMAIL)
</th>
<th>
@Html.DisplayNameFor(model => model.SALARY)
</th>
<th>
@Html.DisplayNameFor(model => model.DOJ)
</th>
<th>
@Html.DisplayNameFor(model => model.PATH)
</th>
<th></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.GENDER)
</td>
<td>
@Html.DisplayFor(modelItem => item.EMAIL)
</td>
<td>
@Html.DisplayFor(modelItem => item.SALARY)
</td>
<td>
@{
string s = string.Format("{0:dd-MM-yyyy}", item.DOJ);
}
@s
</td>
<td>
<img height="50" width="50" src="@("Image/"+item.PATH)"/>
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.EID }) |
@Html.ActionLink("Delete", "Delete", new { id=item.EID })
</td>
</tr>
}
</tbody>
</table>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
var table = $("#tb").DataTable({
"order": [[0, "asc"]],
"lengthMenu": [[2, 10, 25, 50, -1], [2, 10, 25, 50, "All"]],
"scroller": true,
"orderClasses": false,
});
});
</script>
-
@model WebApplication6.Models.NEWEMPVM
@{
ViewData["Title"] = "Create";
}
<div class="row">
<div class="col-md-4">
<form asp-action="Create" enctype="multipart/form-data">
<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="EID" 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">
<label asp-for="GENDER" class="control-label"></label>
<input asp-for="GENDER" type="radio" value="Male" />Male
<input asp-for="GENDER" type="radio" value="Female" />Female
<span asp-validation-for="GENDER" 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="DOJ" class="control-label"></label>
<input asp-for="DOJ" class="form-control" />
<span asp-validation-for="DOJ" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="HOBBY" class="control-label"></label>
<select asp-for="HOBBY" asp-items="Model.Lhobby" class="form-control" multiple></select>
<span asp-validation-for="HOBBY" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="CID" class="control-label"></label>
<select asp-for="CID" asp-items="Model.LCID" class="form-control">
<option value="">Select</option>
</select>
<span asp-validation-for="CID" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="SID" class="control-label"></label>
<select asp-for="SID" asp-items="Model.LSID" class="form-control">
<option value="">Select</option>
</select>
<span asp-validation-for="SID" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="PHOTO" class="control-label"></label>
<input asp-for="PHOTO" type="file" class="form-control" />
<input type="hidden" asp-for="PATH" />
<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>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$('#DOJ').prop("type", "text");
$('#HOBBY').chosen();
$('#DOJ').datetimepicker({
format:'DD-MM-YYYY'
});
var id =@Html.Raw(Json.Serialize(Model.EID));
if (id == 0) {
$('#DOJ').val('');
//$("#PHOTO").rules("remove", "required");
//$("#PHOTO").rules("add", "required");
}
else {
$("#PHOTO").removeAttr('data-val-required');
var dt = new Date(@Html.Raw(Json.Serialize(Model.DOJ)));
$('#DOJ').val((dt.getDate() < 10 ? ("0" + dt.getDate()) : dt.getDate()) + "-" + (parseInt(dt.getMonth() + 1) < 10 ? ("0" + parseInt(dt.getMonth() + 1)) : parseInt(dt.getMonth() + 1)) + "-" + dt.getFullYear());
}
$('#CID').change(function () {
$('#SID').empty().append("<option>Select</option>");
$.ajax({
url: '@Url.Action("Fillddl","NewEmp")',
data: { CID: $(this).val() },
success: function (data) {
$.each(data, function (i, v) {
$('#SID').append("<option value="+v.SID+">"+v.SNAME+"</option>");
});
}
});
});
});
</script>
No comments:
Post a Comment