Models :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using
System.ComponentModel.DataAnnotations;
namespace WebApplication1.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.Linq;
using System.Threading.Tasks;
using
System.ComponentModel.DataAnnotations;
namespace WebApplication1.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.Linq;
using System.Threading.Tasks;
using
System.ComponentModel.DataAnnotations;
namespace WebApplication1.Models
{
public class HOBBY
{
[Key]
public
int HID { get; set; }
public
string DNAME { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using
System.ComponentModel.DataAnnotations;
namespace WebApplication1.Models
{
public class HMAP
{
[Key]
public
int ID { get; set; }
public
int CID { get; set; }
public
int HID { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using
System.ComponentModel.DataAnnotations;
namespace WebApplication1.Models
{
public class INTEREST
{
[Key]
public
int IID { get; set; }
public
string INAME { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
namespace WebApplication1.Models
{
public class IMAP
{
[Key]
public
int ID { get; set; }
public
int CID { 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
System.ComponentModel.DataAnnotations.Schema;
namespace WebApplication1.Models
{
public class CUSTOMER
{
[Key,
DatabaseGenerated(DatabaseGeneratedOption.None)]
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 GENDER { get; set; }
[MaxLength(50)]
public
string EMAIL { get; set; }
public
decimal SALARY { get; set; }
public
DateTime DOJ { get; set; }
public string
PATH { get; set; }
public
int CID { get; set; }
public
int SID { get; set; }
}
}
View Model:
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 WebApplication1.Models
{
public class
CUSTOMERVM
{
public
CUSTOMERVM()
{
HOBBY = new List<SelectListItem>();
LCID = new List<SelectListItem>();
LSID = new List<SelectListItem>();
INTEREST = new List<string>();
LINTEREST = new List<SelectListItem>();
}
[Required(ErrorMessage = "Eid should not be blank.")]
public
int? EID { 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; }
[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; }
[DataType(DataType.Password)]
[Display(Name ="CONFIRM PASSWORD")]
[Required(ErrorMessage = "Confirm password should not be blank.")]
[Compare("PASSWORD",ErrorMessage ="Password and confirm password
must be same.")]
public
string CPASSWORD { get; set; }
[Required(ErrorMessage = "Please select a gender.")]
public
string GENDER { get; set; }
[Required(ErrorMessage = "Email should not be blank.")]
[Remote("Check","Custom",ErrorMessage = "This mail id
is already exists")]
[RegularExpression(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*",
ErrorMessage ="Invalid email id.")]
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 = "Doj should not be blank.")]
public
DateTime DOJ { get; set; }
[Cheboxsvalidation(ErrorMessage ="Please select a hobby.")]
public
List<SelectListItem> HOBBY { get; set; }
[Required(ErrorMessage
= "Please select a country.")]
[Display(Name ="COUNTRY")]
public
int CID { get; set; }
public
List<SelectListItem> LCID { get; set; }
[Required(ErrorMessage = "Please select a state.")]
public
int SID { get; set; }
public
List<SelectListItem> LSID { get; set; }
[Listboxvalidation(ErrorMessage = "Please select a interest.")]
public
List<string> INTEREST { get; set; }
public
List<SelectListItem> LINTEREST { get; set; }
public
string PATH { get; set; }
[Required(ErrorMessage = "Please select a photo.")]
public
IFormFile PHOTO { get; set; }
}
public class
Cheboxsvalidation:ValidationAttribute
{
public
override bool IsValid(object value)
{
if (value == null)
return false;
else
return ((List<SelectListItem>)value).Count(m =>
m.Selected) > 0;
}
}
public class
Listboxvalidation:ValidationAttribute
{
public
override bool IsValid(object value)
{
if (value == null)
return false;
else
return ((List<string>)value).Count > 0;
}
}
}
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 id)
{
var data = await Get(id);
context.Set<T>().Remove(data);
await context.SaveChangesAsync();
}
public
async Task Multipledelete(List<T> t)
{
context.Set<T>().RemoveRange(t);
await context.SaveChangesAsync();
}
public
async Task<T> Get(int id)
{
return await context.Set<T>().FindAsync(id);
}
public IQueryable<T> Gets()
{
return context.Set<T>().AsNoTracking();
}
public
async Task Multiplesave(List<T> t)
{
await context.Set<T>().AddRangeAsync(t);
await context.SaveChangesAsync();
}
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();
}
}
}
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 id)
{
var data = await Get(id);
context.Set<T>().Remove(data);
await context.SaveChangesAsync();
}
public
async Task Multipledelete(List<T> t)
{
context.Set<T>().RemoveRange(t);
await context.SaveChangesAsync();
}
public
async Task<T> Get(int id)
{
return await context.Set<T>().FindAsync(id);
}
public IQueryable<T> Gets()
{
return context.Set<T>().AsNoTracking();
}
public
async Task Multiplesave(List<T> t)
{
await context.Set<T>().AddRangeAsync(t);
await context.SaveChangesAsync();
}
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();
}
}
}
DbContext :
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<COUNTRY> COUNTRIEs { get; set; }
public
DbSet<STATE> STATEs { get; set; }
public
DbSet<HOBBY> HOBBY { get; set; }
public
DbSet<HMAP> HMAP { get; set; }
public
DbSet<INTEREST> INTEREST { get; set; }
public
DbSet<IMAP> IMAP { get; set; }
public
DbSet<CUSTOMER> CUSTOMER { get; set; }
}
}
Add connection string in
appsettings.json :
{
"Logging": {
"LogLevel":
{
"Default": "Warning"
}
},
"AllowedHosts":
"*",
"ConnectionStrings": {
"DBConnection":
"server=(localdb)\\MSSQLLocalDB;database=SIVDB;Trusted_Connection=true;MultipleActiveResultSets=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.AddDbContext<AppDbContext>();
services.AddScoped<IRepository<COUNTRY>,
Repository<COUNTRY>>();
services.AddScoped<IRepository<STATE>,
Repository<STATE>>();
services.AddScoped<IRepository<CUSTOMER>,
Repository<CUSTOMER>>();
services.AddScoped<IRepository<HOBBY>,
Repository<HOBBY>>();
services.AddScoped<IRepository<HMAP>,
Repository<HMAP>>();
services.AddScoped<IRepository<INTEREST>,
Repository<INTEREST>>();
services.AddScoped<IRepository<IMAP>,
Repository<IMAP>>();
}
// 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=Custom}/{action=Index}/{id?}");
});
}
}
}
Use 2 commands for migration :
Add-Migration Intialmigraion
Update-Database
Controller :
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
using
Microsoft.AspNetCore.Mvc.Rendering;
using System.IO;
using Microsoft.AspNetCore.Hosting;
namespace
WebApplication1.Controllers
{
public class
CustomController : Controller
{
#region
private
readonly IRepository<CUSTOMER> rCUSTOMER;
private
readonly IRepository<COUNTRY> rCOUNTRY;
private
readonly IRepository<STATE> rSTATE;
private
readonly IRepository<HOBBY> rHOBBY;
private
readonly IRepository<HMAP> rHMAP;
private
readonly IRepository<INTEREST> rINTEREST;
private
readonly IRepository<IMAP> rIMAP;
private
readonly IHostingEnvironment hostingEnvironment;
#endregion
public
CustomController(IRepository<CUSTOMER> RCUSTOMER,
IRepository<COUNTRY> RCOUNTRY,
IRepository<STATE> RSTATE,
IRepository<HOBBY> RHOBBY,
IRepository<HMAP> RHMAP,
IRepository<INTEREST> RINTEREST,
IRepository<IMAP> RIMAP,
IHostingEnvironment HostingEnvironment)
{
this.rCUSTOMER = RCUSTOMER;
this.rCOUNTRY = RCOUNTRY;
this.rSTATE = RSTATE;
this.rHOBBY = RHOBBY;
this.rHMAP = RHMAP;
this.rINTEREST = RINTEREST;
this.rIMAP = RIMAP;
this.hostingEnvironment = HostingEnvironment;
}
[HttpGet]
public
IActionResult Index()
{
return View(rCUSTOMER.Gets());
}
[HttpGet]
public
JsonResult Fillddl(int CID)
{
return Json(JsonConvert.SerializeObject(rSTATE.Gets().Where(m =>
m.CID == CID).ToList()));
}
[HttpGet]
public
IActionResult Create()
{
CUSTOMERVM vm = new CUSTOMERVM();
vm.HOBBY = rHOBBY.Gets().Select(x => new SelectListItem {
Value=x.HID.ToString(), Text=x.DNAME }).ToList();
vm.LCID =rCOUNTRY.Gets().Select(x => new SelectListItem { Value =
x.CID.ToString(), Text = x.CNAME }).ToList();
vm.LINTEREST = rINTEREST.Gets().Select(x => new SelectListItem {
Value = x.IID.ToString(), Text = x.INAME }).ToList();
return View(vm);
}
[HttpPost]
public
IActionResult Create(CUSTOMERVM vm)
{
if (ModelState.IsValid)
{
CUSTOMER cUSTOMER = new CUSTOMER();
cUSTOMER.EID = vm.EID??0;
cUSTOMER.NAME = vm.NAME;
cUSTOMER.ADDRESS = vm.ADDRESS;
cUSTOMER.PASSWORD = vm.PASSWORD;
cUSTOMER.GENDER = vm.GENDER;
cUSTOMER.EMAIL = vm.EMAIL;
cUSTOMER.SALARY = vm.SALARY;
cUSTOMER.DOJ = vm.DOJ;
cUSTOMER.CID = vm.CID;
cUSTOMER.SID = vm.SID;
string uniqueFileName = null;
string filePath = null;
string uploadsFolder = string.Empty;
if (vm.PHOTO != null)
{
uploadsFolder =
Path.Combine(hostingEnvironment.WebRootPath, "images");
// To make sure the file name is unique we
are appending a new
// GUID value and and an underscore to the
file name
uniqueFileName = Guid.NewGuid().ToString() +
"_" + vm.PHOTO.FileName;
filePath = Path.Combine(uploadsFolder,
uniqueFileName);
// Use CopyTo() method provided by IFormFile
interface to
// copy the file to wwwroot/images folder
vm.PHOTO.CopyTo(new FileStream(filePath,
FileMode.Create));
}
cUSTOMER.PATH =uniqueFileName;
rCUSTOMER.Save(cUSTOMER);
rHMAP.Multiplesave(vm.HOBBY.Where(n=>n.Selected).Select(x => new HMAP {
CID =vm.EID.Value, HID = Convert.ToInt32(x.Value) }).ToList());
rIMAP.Multiplesave(vm.INTEREST.Select(x => new IMAP {
CID = vm.EID.Value, IID = Convert.ToInt32(x) }).ToList());
return RedirectToAction("Index");
}
else
{
vm.HOBBY = rHOBBY.Gets().Select(x => new SelectListItem
{ Value = x.HID.ToString(), Text = x.DNAME }).ToList();
vm.LCID = rCOUNTRY.Gets().Select(x => new
SelectListItem { Value = x.CID.ToString(), Text = x.CNAME }).ToList();
vm.LSID = rSTATE.Gets().Where(M => M.CID ==
vm.CID).Select(x => new SelectListItem { Value = x.SID.ToString(), Text = x.SNAME
}).ToList();
vm.LINTEREST = rINTEREST.Gets().Select(x => new
SelectListItem { Value = x.IID.ToString(), Text = x.INAME }).ToList();
return View(vm);
}
}
[HttpGet]
public
IActionResult Edit(int id)
{
CUSTOMERVM vm = new CUSTOMERVM();
CUSTOMER cUSTOMER = rCUSTOMER.Get(id).Result;
vm.EID = cUSTOMER.EID;
vm.NAME = cUSTOMER.NAME;
vm.ADDRESS = cUSTOMER.ADDRESS;
vm.GENDER = cUSTOMER.GENDER;
vm.EMAIL = cUSTOMER.EMAIL;
vm.SALARY = cUSTOMER.SALARY;
vm.DOJ = cUSTOMER.DOJ;
vm.CID = cUSTOMER.CID;
vm.SID = cUSTOMER.SID;
vm.LCID = rCOUNTRY.Gets().Select(x => new SelectListItem { Value =
x.CID.ToString(), Text = x.CNAME }).ToList();
vm.LSID = rSTATE.Gets().Where(m=>m.CID==vm.CID).Select(x => new
SelectListItem { Value = x.SID.ToString(), Text = x.SNAME }).ToList();
vm.LINTEREST = rINTEREST.Gets().Select(x => new SelectListItem {
Value = x.IID.ToString(), Text = x.INAME }).ToList();
vm.INTEREST = rIMAP.Gets().Where(n => n.CID == vm.EID).Select(m =>
m.IID.ToString()).ToList();
List<SelectListItem> hlst = new List<SelectListItem>();
int mark = 0;
var hobby = rHOBBY.Gets().ToList();
var mhobby = rHMAP.Gets().Where(m => m.CID == vm.EID).ToList();
foreach (HOBBY hb in hobby)
{
mark = 0;
foreach (HMAP hm in mhobby)
{
if (hb.HID == hm.HID)
{
mark = 1;
break;
}
}
if (mark == 1)
hlst.Add(new SelectListItem {
Value=hb.HID.ToString(), Text=hb.DNAME, Selected=true });
else
hlst.Add(new SelectListItem { Value =
hb.HID.ToString(), Text = hb.DNAME, Selected =false });
}
vm.HOBBY = hlst;
return View(vm);
}
[HttpPost]
public
IActionResult Edit(CUSTOMERVM vm)
{
ModelState.Remove("PASSWORD");
ModelState.Remove("CPASSWORD");
ModelState.Remove("PHOTO");
if (ModelState.IsValid)
{
CUSTOMER cUSTOMER = rCUSTOMER.Get(vm.EID.Value).Result;
cUSTOMER.NAME = vm.NAME;
cUSTOMER.ADDRESS = vm.ADDRESS;
cUSTOMER.GENDER = vm.GENDER;
cUSTOMER.EMAIL = vm.EMAIL;
cUSTOMER.SALARY = vm.SALARY;
cUSTOMER.DOJ = vm.DOJ;
cUSTOMER.CID = vm.CID;
cUSTOMER.SID = vm.SID;
string uniqueFileName = null;
string filePath = null;
string uploadsFolder = string.Empty;
if (vm.PHOTO != null)
{
uploadsFolder =
Path.Combine(hostingEnvironment.WebRootPath, "images");
// To make sure the file name is unique we
are appending a new
// GUID value and and an underscore to the
file name
uniqueFileName = Guid.NewGuid().ToString() +
"_" + vm.PHOTO.FileName;
filePath = Path.Combine(uploadsFolder,
uniqueFileName);
// Use CopyTo() method provided by IFormFile
interface to
// copy the file to wwwroot/images folder
vm.PHOTO.CopyTo(new FileStream(filePath,
FileMode.Create));
cUSTOMER.PATH = uniqueFileName;
}
var data = rHMAP.Gets().Where(m => m.CID ==
vm.EID.Value).ToList();
var data1 = rIMAP.Gets().Where(m => m.CID ==
vm.EID.Value).ToList();
rCUSTOMER.Update(cUSTOMER);
foreach (HMAP hm in data)
rHMAP.Delete(hm.ID);
rHMAP.Multiplesave(vm.HOBBY.Where(n =>
n.Selected).Select(x => new HMAP { CID = vm.EID.Value, HID =
Convert.ToInt32(x.Value) }).ToList());
foreach (IMAP im in data1)
rIMAP.Delete(im.ID);
rIMAP.Multiplesave(vm.INTEREST.Select(x => new IMAP {
CID = vm.EID.Value, IID = Convert.ToInt32(x) }).ToList());
return RedirectToAction("Index");
}
else
{
vm.HOBBY = rHOBBY.Gets().Select(x => new SelectListItem
{ Value = x.HID.ToString(), Text = x.DNAME }).ToList();
vm.LCID = rCOUNTRY.Gets().Select(x => new
SelectListItem { Value = x.CID.ToString(), Text = x.CNAME }).ToList();
vm.LSID = rSTATE.Gets().Where(M => M.CID == vm.CID).Select(x
=> new SelectListItem { Value = x.SID.ToString(), Text = x.SNAME
}).ToList();
vm.LINTEREST = rINTEREST.Gets().Select(x => new
SelectListItem { Value = x.IID.ToString(), Text = x.INAME }).ToList();
return View(vm);
}
}
[HttpGet]
public
IActionResult Check(string EMAIL)
{
if (EMAIL == null)
return Json(false);
else
return Json(!rCUSTOMER.Gets().Any(m => m.EMAIL ==
EMAIL));
}
[HttpPost]
public
IActionResult DeleteAll(List<int> Lst)
{
rCUSTOMER.Multipledelete(rCUSTOMER.Gets().Where(n=>Lst.Contains(n.EID)).ToList());
rHMAP.Multipledelete(rHMAP.Gets().Where(p=>Lst.Contains(p.CID)).ToList());
rIMAP.Multipledelete(rIMAP.Gets().Where(m=>Lst.Contains(m.CID)).ToList());
return Json("1");
}
[HttpGet]
public
IActionResult Delete(int id)
{
var data = rHMAP.Gets().Where(m => m.CID == id).ToList();
var data1 = rIMAP.Gets().Where(m => m.CID == id).ToList();
rCUSTOMER.Delete(id);
foreach (HMAP hm in data)
rHMAP.Delete(hm.ID);
foreach (IMAP im in data1)
rIMAP.Delete(im.ID);
return RedirectToAction("Index");
}
}
}
Index View :
@model IEnumerable<CUSTOMER>
@{
ViewData["Title"] = "Index";
}
<p
style="margin-top:5px">
<a
asp-action="Create" class="btn btn-primary"
style="width:80px">Create</a>
</p>
<div style="border:1px solid
#000000">
<table
class="table table-condensed table-hover table-responsive"
id="tb">
<thead
class="bg bg-primary">
<tr>
<th>
<input type="checkbox"
class="hcb" />
</th>
<th>
@Html.DisplayNameFor(model => model.EID)
</th>
<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>
PHOTO
</th>
<th>ACTION</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
<input
type="checkbox" value="@item.EID" class="cb"
/>
</td>
<td>
@Html.DisplayFor(modelItem
=> item.EID)
</td>
<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-MMM-yy}", item.DOJ);
}
@s
</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>
</div>
<p
style="margin-top:2px">
<input type="button"
class="btn btn-primary" value="Delete All"
id="btnDel" />
</p>
@section Scripts {
@{await
Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script
type="text/javascript">
$(function () {
$('#tb').on("click", ".hcb", function () {
$(".cb").attr("checked",
this.checked);
});
$('#tb').on("click", ".cb", function () {
if ($('.cb').length == $('.cb:checked').length)
$(".hcb").attr("checked", true);
else
$(".hcb").attr("checked", false);
});
var table = $("#tb").DataTable({
"order": [[0, "asc"]],
"lengthMenu": [[2, 10, 25, 50, -1], [2, 10, 25,
50, "All"]],
"scroller": true,
"orderClasses": false,
});
$('#btnDel').click(function () {
if ($('#tb').find('.cb:checked').length == 0) {
alert('Please select a item from the list.')
return;
}
var ids = [];
if (confirm('Do you want to delete it ?')) {
$('#tb').find('.cb:checked').each(function
(i, j) {
ids.push(j.value);
});
$.ajax({
"url":
'@Url.Action("DeleteAll", "Custom")',
type: 'Post',
datatype: 'json',
cache: false,
async: true,
data: { Lst: ids },
success: function (data) {
if (data == 1)
window.location.reload(true);
}
});
}
});
})
</script>
}
Create View :
@model CUSTOMERVM
@{
ViewData["Title"] = "Create";
}
<div class="row">
<div
class="col-md-4">
<form
asp-action="Create" asp-controller="Custom"
method="post" enctype="multipart/form-data">
<div asp-validation-summary="ModelOnly"
class="text-danger"></div>
<div class="form-group">
<label asp-for="EID"
class="control-label"></label>
<input asp-for="EID"
class="form-control" />
<span asp-validation-for="EID"
class="text-danger"></span>
</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="GENDER"
class="control-label"></label>
<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="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 autocomplete="off"
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>
@for (int i = 0; i < Model.HOBBY.Count(); i++)
{
<input type="hidden"
asp-for="@Model.HOBBY[i].Text" />
<input type="hidden"
asp-for="@Model.HOBBY[i].Value" />
<input
asp-for="@Model.HOBBY[i].Selected" class="form-check-input"
/>
<label class="form-check-label"
asp-for="@Model.HOBBY[i].Selected">
@Model.HOBBY[i].Text
</label>
}
<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="INTEREST"
class="control-label"></label>
<select asp-for="INTEREST" multiple
asp-items="Model.LINTEREST"
class="form-control"></select>
<span asp-validation-for="INTEREST"
class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="PHOTO"
class="control-label"></label>
<input type="file" asp-for="PHOTO"
class="form-control" />
<span asp-validation-for="PHOTO"
class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create"
class="btn btn-default" />
</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 () {
$('#DOJ').prop("type", "");
$('#DOJ').val("");
$('#INTEREST').multiselect();
$('#DOJ').datepicker();
$('#CID').change(function () {
$.ajax({
url: '@Url.Action("Fillddl",
"Custom")',
data: { CID: $(this).val() },
type: 'GET',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (result) {
$('#SID').empty();
$('#SID').append("<option
value=''>Select</option>");
$.each(JSON.parse(result), function (i, j) {
$('#SID').append("<option value='" + j.SID + "'>" +
j.SNAME + "</option>");
});
}
});
});
});
</script>
}
Edit View :
@model CUSTOMERVM
@{
ViewData["Title"] = "Edit";
}
<div class="row">
<div
class="col-md-4">
<form
asp-action="Edit" asp-controller="Custom"
method="post" 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 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="GENDER"
class="control-label"></label>
<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="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 autocomplete="off"
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>
@for (int i = 0; i < Model.HOBBY.Count(); i++)
{
<input type="hidden"
asp-for="@Model.HOBBY[i].Text" />
<input type="hidden"
asp-for="@Model.HOBBY[i].Value" />
<input
asp-for="@Model.HOBBY[i].Selected" class="form-check-input"
/>
<label class="form-check-label"
asp-for="@Model.HOBBY[i].Selected">
@Model.HOBBY[i].Text
</label>
}
<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="INTEREST"
class="control-label"></label>
<select asp-for="INTEREST" multiple
asp-items="Model.LINTEREST" class="form-control"></select>
<span asp-validation-for="INTEREST"
class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="PHOTO"
class="control-label"></label>
<input type="file"
asp-for="PHOTO" class="form-control" />
<span asp-validation-for="PHOTO"
class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" id="btn"
value="Create" class="btn btn-default" />
</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 () {
$("#PHOTO").rules("remove", "required")
$("#EMAIL").rules("remove", "remote")
$('#DOJ').prop("type", "");
$('#INTEREST').multiselect();
$('#DOJ').datepicker();
$('#CID').change(function () {
$.ajax({
url: '@Url.Action("Fillddl",
"Custom")',
data: { CID: $(this).val() },
type: 'GET',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (result) {
$('#SID').empty();
$('#SID').append("<option
value=''>Select</option>");
$.each(JSON.parse(result), function (i, j) {
$('#SID').append("<option value='" + j.SID + "'>" +
j.SNAME + "</option>");
});
}
});
});
});
</script>
}
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="~/css/site.css" />
<link
href="~/css/DataTables/css/jquery.dataTables.css"
rel="stylesheet" />
<link href="~/css/DataTables/css/jquery.dataTables_themeroller.css"
rel="stylesheet" />
<link href="~/css/jquery.multiselect.css"
rel="stylesheet" />
<link
rel="stylesheet"
href="~/lib/bootstrap/dist/css/bootstrap.css" />
</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>© 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="~/js/multiselect.js"></script>
<script
src="~/js/DataTables/jquery.dataTables.js"></script>
<script
src="~/lib/bootstrap/dist/js/bootstrap.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>
How to Save date in MVC6 using
jquery:
Controller :
[HttpPost]
public
IActionResult Add(JBS vm)
{
JRepository.Save(vm);
return Json("Data Saved.");
}
View :
@model JBSVM;
@{
ViewData["Title"] = "Add";
}
<form
class="form-horizontal" style="margin-top:20px">
<div
class="form-group">
<label class="control-label col-lg-4">EID</label>
<div
class="col-lg-4">
<input type="text" class="form-control"
id="eid" />
</div>
</div>
<div
class="form-group">
<label class="control-label col-lg-4">NAME</label>
<div
class="col-lg-4">
<input type="text" class="form-control"
id="name" />
</div>
</div>
<div
class="form-group">
<label class="control-label col-lg-4"></label>
<div
class="col-lg-4">
<input type="button" class="btn btn-primary"
value="Save" style="width:80px" id="btn" />
</div>
</div>
</form>
@section Scripts {
@{await
Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script
type="text/javascript">
$('#btn').click(function () {
$.ajax({
"url":
'@Url.Action("Add", "Jagannath")',
type: 'Post',
datatype: 'json',
cache: false,
async: true,
data: { JID: $('#eid').val(), NAME:
$('#name').val() },
success: function (data) {
alert(data);
window.location.href =
"Index";
},
error: function (t) {
alert(t.responseText);
}
});
})
</script>
}
No comments:
Post a Comment