First go VS view menu select SQL Server Object Explorer from the menu
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
View Model :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc.Rendering;
namespace WebApplication2.Models
{
public class EMPVM
{
public EMPVM()
{
Lhobby = new List<SelectListItem>();
Lcid = new List<SelectListItem>();
Lsid = new List<SelectListItem>();
Iid = new List<string>();
Liid = new List<SelectListItem>();
}
public int? eid { get; set; }
public string Name { get; set; }
[DataType(DataType.MultilineText)]
public string Address { get; set; }
[DataType(DataType.Password)]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name ="Confirm Password")]
public string CPassword { get; set; }
public string Gender { get; set; }
public DateTime? Doj { get; set; }
public string Salary { get; set; }
public string Email { get; set; }
[Display(Name="Hobby")]
public List<SelectListItem> Lhobby { get; set; }
[Display(Name ="Country")]
public int? Cid { get; set; }
public List<SelectListItem> Lcid { get; set; }
[Display(Name ="State")]
public int? Sid { get; set; }
public List<SelectListItem> Lsid { get; set; }
[Display(Name ="Interest")]
public List<string> Iid { get; set; }
public List<SelectListItem> Liid { get; set; }
}
}
SankarContext :
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
namespace WebApplication2.DAL
{
public partial class SankarContext : DbContext
{
public SankarContext()
{
}
public SankarContext(DbContextOptions<SankarContext> options)
: base(options)
{
}
public virtual DbSet<Country> Country { get; set; }
public virtual DbSet<Dept> Dept { get; set; }
public virtual DbSet<Emp> Emp { get; set; }
public virtual DbSet<Emp1> Emp1 { get; set; }
public virtual DbSet<Hmap> Hmap { get; set; }
public virtual DbSet<Hobby> Hobby { get; set; }
public virtual DbSet<Imap> Imap { get; set; }
public virtual DbSet<Interest> Interest { get; set; }
public virtual DbSet<State> State { get; set; }
public virtual DbSet<Test> Test { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer("Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=Sankar;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False");
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Country>(entity =>
{
entity.HasKey(e => e.Cid);
entity.ToTable("COUNTRY");
entity.Property(e => e.Cid)
.HasColumnName("CID")
.ValueGeneratedNever();
entity.Property(e => e.Cname)
.HasColumnName("CNAME")
.HasMaxLength(50);
});
modelBuilder.Entity<Dept>(entity =>
{
entity.HasKey(e => e.Did);
entity.ToTable("DEPT");
entity.Property(e => e.Did)
.HasColumnName("DID")
.ValueGeneratedNever();
entity.Property(e => e.Dname)
.HasColumnName("DNAME")
.HasMaxLength(50);
});
modelBuilder.Entity<Test>(entity =>
{
entity.HasKey(e => e.Tid);
entity.ToTable("TEST");
entity.Property(e => e.Tid)
.HasColumnName("TID")
.ValueGeneratedNever();
entity.Property(e => e.Name)
.HasColumnName("NAME")
.HasMaxLength(50);
});
modelBuilder.Entity<Emp>(entity =>
{
entity.HasKey(e => e.Eid);
entity.ToTable("EMP");
entity.Property(e => e.Eid)
.HasColumnName("EID")
.ValueGeneratedNever();
entity.Property(e => e.Address).HasColumnName("ADDRESS");
entity.Property(e => e.Cid).HasColumnName("CID");
entity.Property(e => e.Doj)
.HasColumnName("DOJ")
.HasColumnType("date");
entity.Property(e => e.Email)
.HasColumnName("EMAIL")
.HasMaxLength(50);
entity.Property(e => e.Gender)
.HasColumnName("GENDER")
.HasMaxLength(50);
entity.Property(e => e.Name)
.HasColumnName("NAME")
.HasMaxLength(50);
entity.Property(e => e.Password)
.HasColumnName("PASSWORD")
.HasMaxLength(50);
entity.Property(e => e.Salary)
.HasColumnName("SALARY")
.HasMaxLength(50);
entity.Property(e => e.Sid).HasColumnName("SID");
});
modelBuilder.Entity<Emp1>(entity =>
{
entity.HasKey(e => e.Eid);
entity.ToTable("EMP1");
entity.Property(e => e.Eid)
.HasColumnName("EID")
.ValueGeneratedNever();
entity.Property(e => e.Did).HasColumnName("DID");
entity.Property(e => e.Name)
.HasColumnName("NAME")
.HasMaxLength(50);
});
modelBuilder.Entity<Hmap>(entity =>
{
entity.ToTable("HMAP");
entity.Property(e => e.Id).HasColumnName("ID");
entity.Property(e => e.Eid).HasColumnName("EID");
entity.Property(e => e.Hid).HasColumnName("HID");
});
modelBuilder.Entity<Hobby>(entity =>
{
entity.HasKey(e => e.Hid);
entity.ToTable("HOBBY");
entity.Property(e => e.Hid)
.HasColumnName("HID")
.ValueGeneratedNever();
entity.Property(e => e.Hname)
.HasColumnName("HNAME")
.HasMaxLength(50);
});
modelBuilder.Entity<Imap>(entity =>
{
entity.ToTable("IMAP");
entity.Property(e => e.Id).HasColumnName("ID");
entity.Property(e => e.Eid).HasColumnName("EID");
entity.Property(e => e.Iid).HasColumnName("IID");
});
modelBuilder.Entity<Interest>(entity =>
{
entity.HasKey(e => e.Iid);
entity.ToTable("INTEREST");
entity.Property(e => e.Iid)
.HasColumnName("IID")
.ValueGeneratedNever();
entity.Property(e => e.Iname)
.HasColumnName("INAME")
.HasMaxLength(50);
});
modelBuilder.Entity<State>(entity =>
{
entity.HasKey(e => e.Sid);
entity.ToTable("STATE");
entity.Property(e => e.Sid)
.HasColumnName("SID")
.ValueGeneratedNever();
entity.Property(e => e.Cid).HasColumnName("CID");
entity.Property(e => e.Sname)
.HasColumnName("SNAME")
.HasMaxLength(50);
});
}
}
}
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.EntityFrameworkCore;
using Microsoft.AspNetCore.Mvc.Rendering;
using Newtonsoft.Json;
namespace WebApplication2.Controllers
{
public class EmpController : Controller
{
[HttpGet]
public async Task<IActionResult> Index()
{
using (SankarContext obj = new SankarContext())
{
var data = await obj.Emp.ToListAsync();
if (data == null)
return NoContent();
return View(data);
}
}
[HttpGet]
public async Task<IActionResult> Fillddl(int CID)
{
using (SankarContext obj = new SankarContext())
{
return Json(JsonConvert.SerializeObject(await obj.State.Where(m => m.Cid == CID).ToListAsync()));
}
}
[HttpPost]
public async Task<IActionResult> Create(EMPVM vm)
{
using (SankarContext obj = new SankarContext())
{
Emp emp = new Emp();
emp.Eid = vm.eid.Value;
emp.Name = vm.Name;
emp.Address = vm.Address;
emp.Password = vm.Password;
emp.Gender = vm.Gender;
emp.Doj = vm.Doj;
emp.Salary = vm.Salary;
emp.Email = vm.Email;
emp.Cid = vm.Cid;
emp.Sid = vm.Sid;
await obj.Emp.AddAsync(emp);
await obj.SaveChangesAsync();
await obj.Hmap.AddRangeAsync(vm.Lhobby.Where(n => n.Selected == true).Select(m => new Hmap { Eid = vm.eid, Hid = Convert.ToInt32(m.Value) }).ToList());
await obj.SaveChangesAsync();
await obj.Imap.AddRangeAsync(vm.Iid.Select(m => new Imap { Eid = vm.eid, Iid = Convert.ToInt32( m )}).ToList());
await obj.SaveChangesAsync();
}
return RedirectToAction("Index");
}
[HttpGet]
public async Task<IActionResult> Create()
{
using (SankarContext obj = new SankarContext())
{
EMPVM vm = new EMPVM();
vm.Lhobby = await obj.Hobby.Select(m=>new SelectListItem { Value=m.Hid.ToString(), Text=m.Hname }).ToListAsync();
vm.Lcid = await obj.Country.Select(n => new SelectListItem { Value = n.Cid.ToString(), Text = n.Cname }).ToListAsync();
vm.Liid = await obj.Interest.Select(p => new SelectListItem { Value = p.Iid.ToString(), Text = p.Iname }).ToListAsync();
return View(vm);
}
}
[HttpGet]
public async Task<IActionResult> Gets()
{
using (SankarContext obj = new SankarContext())
{
return Json(JsonConvert.SerializeObject(await obj.Emp.ToListAsync()));
}
}
[HttpGet]
public async Task<IActionResult> Edit(int id)
{
using (SankarContext obj = new SankarContext())
{
Emp emp = obj.Emp.Find(id);
EMPVM vm = new EMPVM();
vm.eid = emp.Eid;
vm.Name = emp.Name;
vm.Address = emp.Address;
vm.Gender = emp.Gender;
vm.Doj = emp.Doj;
vm.Salary = emp.Salary;
vm.Email = emp.Email;
vm.Cid = emp.Cid;
vm.Sid = emp.Sid;
vm.Lcid = await obj.Country.Select(n => new SelectListItem { Value = n.Cid.ToString(), Text = n.Cname }).ToListAsync();
vm.Lsid = await obj.State.Where(m => m.Cid == emp.Cid).Select(n => new SelectListItem { Value = n.Sid.ToString(), Text = n.Sname }).ToListAsync();
vm.Liid = await obj.Interest.Select(p => new SelectListItem { Value = p.Iid.ToString(), Text = p.Iname }).ToListAsync();
vm.Iid = await obj.Imap.Where(m => m.Eid == emp.Eid).Select(n => n.Iid.ToString()).ToListAsync();
List<SelectListItem> lst = new List<SelectListItem>();
int mark = 0;
foreach (Hobby hb in obj.Hobby.ToList())
{
mark = 0;
foreach (Hmap hm in obj.Hmap.Where(n=>n.Eid==emp.Eid).ToList())
{
if (hb.Hid == hm.Hid)
{
mark = 1;
break;
}
}
if (mark == 1)
lst.Add(new SelectListItem { Value = hb.Hid.ToString(), Text = hb.Hname, Selected = true });
else
lst.Add(new SelectListItem { Value = hb.Hid.ToString(), Text = hb.Hname, Selected = false });
}
vm.Lhobby = lst;
return View(vm);
}
}
[HttpPost]
public async Task<IActionResult> Edit(EMPVM vm)
{
using (SankarContext obj = new SankarContext())
{
Emp emp = await obj.Emp.SingleOrDefaultAsync(m => m.Eid == vm.eid);
emp.Name = vm.Name;
emp.Address = vm.Address;
emp.Gender = vm.Gender;
emp.Doj = vm.Doj;
emp.Salary = vm.Salary;
emp.Email = vm.Email;
emp.Cid = vm.Cid;
emp.Sid = vm.Sid;
obj.Emp.Update(emp);
await obj.SaveChangesAsync();
obj.Hmap.RemoveRange(obj.Hmap.Where(n => n.Eid == emp.Eid).ToList());
await obj.SaveChangesAsync();
await obj.Hmap.AddRangeAsync(vm.Lhobby.Where(n => n.Selected == true).Select(m => new Hmap { Eid = vm.eid, Hid = Convert.ToInt32(m.Value) }).ToList());
await obj.SaveChangesAsync();
obj.Imap.RemoveRange(obj.Imap.Where(p => p.Eid == emp.Eid).ToList());
await obj.SaveChangesAsync();
await obj.Imap.AddRangeAsync(vm.Iid.Select(m => new Imap { Eid = vm.eid, Iid = Convert.ToInt32(m) }).ToList());
await obj.SaveChangesAsync();
}
return RedirectToAction("Index");
}
[HttpGet]
public async Task<IActionResult> Delete(int id)
{
using (SankarContext obj = new SankarContext())
{
obj.Emp.Remove(obj.Emp.Find(id));
await obj.SaveChangesAsync();
obj.Hmap.RemoveRange(obj.Hmap.Where(n => n.Eid == id).ToList());
await obj.SaveChangesAsync();
obj.Imap.RemoveRange(obj.Imap.Where(p => p.Eid == id).ToList());
await obj.SaveChangesAsync();
return RedirectToAction("Index");
}
}
[HttpPost]
public async Task<IActionResult> DeleteAll(List<int> lst)
{
using (SankarContext obj = new SankarContext())
{
obj.Emp.RemoveRange(await obj.Emp.Where(m => lst.Contains(m.Eid)).ToListAsync());
await obj.SaveChangesAsync();
obj.Hmap.RemoveRange(await obj.Hmap.Where(m => lst.Contains(m.Eid.Value)).ToListAsync());
await obj.SaveChangesAsync();
obj.Imap.RemoveRange(await obj.Imap.Where(n => lst.Contains(n.Eid.Value)).ToListAsync());
await obj.SaveChangesAsync();
return Json("1");
}
}
}
}
Index View :
@model IEnumerable<WebApplication2.DAL.Emp>
@{
ViewData["Title"] = "Index";
}
<br />
<p>
<a asp-action="Create" class="btn btn-primary">Add New</a>
</p>
<div style="border:solid 1px #000000; margin-top:2px">
<br />
<table class="table table-condensed table-hover table-responsive table-striped" id="example">
<thead class="bg bg-primary">
<tr>
<th><input name="select_all" value="0" id="example-select-all" type="checkbox" /></th>
<th>
EID
</th>
<th>
NAME
</th>
<th>
ADDRESS
</th>
<th>
GENDER
</th>
<th>
DOJ
</th>
<th>
SALARY
</th>
<th>
EMAIL
</th>
<th>ACTION</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<br />
<p>
<a id="btndel" class="btn btn-primary">Delete All</a>
</p>
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script type="text/javascript">
$(function () {
var table;
$.ajax({
"url": "@Url.Action("Gets", "Emp")",
type: 'Get',
datatype: 'json',
cache: false,
success: function (Data1) {
var Data = JSON.parse(Data1);
table = $('#example').DataTable({
data: Data,
"pagingType": "full_numbers",
"lengthMenu": [[2, 10, 25, 50, -1], [2, 10, 25, 50, "All"]],
columns: [
{
data: "Eid",
render: function (data, type, full, meta) {
return '<input type="checkbox" name="id[]" value="'
+ data + '">';
}
},
{ data: "Eid" },
{ data: "Name" },
{ data: "Address" },
{ data: "Gender" },
{ data: "Doj"},
{ data: "Salary" },
{ data: "Email" },
{
data: "Eid",
render: function (eid) {
return '<a onClick="edit(' + eid + ')">Edit</a> | <a onClick="del(' + eid + ')">Delete</a>';
}
},
],
select: {
style: 'multi'
},
order: [[1, 'asc']]
});
}
});
// Handle click on "Select all" control
$('#example-select-all').on('click', function () {
// Check/uncheck all checkboxes in the table
var rows = table.rows({ 'search': 'applied' }).nodes();
$('input[type="checkbox"]', rows).prop('checked', this.checked);
});
$('#example tbody').on('change', 'input[type="checkbox"]', function () {
// If checkbox is not checked
if (!this.checked) {
var el = $('#example-select-all').get(0);
// If "Select all" control is checked and has 'indeterminate' property
if (el && el.checked && ('indeterminate' in el)) {
// Set visual state of "Select all" control
// as 'indeterminate'
el.indeterminate = true;
}
}
});
var checkIds = [];
$('#btndel').click(function () {
if (table.$('input[type="checkbox"]:checked').length == 0) {
alert('Please select a item from the gride.');
return;
}
if (confirm('Do you want to delete it ?')) {
table.$('input[type="checkbox"]').each(function () {
if (this.checked) {
checkIds.push((this.value));
}
});
$.ajax({
"url": "@Url.Action("DeleteAll", "Emp")",
type: 'Post',
datatype: 'json',
cache: false,
data: { lst: checkIds },
success: function (data) {
if (data == 1)
window.location.reload(true);
}
});
}
});
});
function edit(id) {
window.location.href = "Emp/Edit/" + id;
}
function del(id) {
window.location.href = "Emp/Delete/" + id;
}
</script>
}
Create View :
@model WebApplication2.Models.EMPVM
@{
ViewData["Title"] = "Create";
}
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="eid" class="control-label"></label>
<input asp-for="eid" class="form-control" />
<span asp-validation-for="eid" id="reid" 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" id="rName" 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" id="rAddress" 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" id="rPassword" 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" id="rCPassword" 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" id="rGender" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Doj" class="control-label"></label>
<input asp-for="Doj" autocomplete="off" class="form-control" />
<span asp-validation-for="Doj" id="rDoj" 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" id="rSalary" 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" id="rEmail" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Lhobby" class="control-label"></label>
@for (int i = 0; i < Model.Lhobby.Count; i++)
{
<input type="hidden" asp-for="@Model.Lhobby[i].Text" />
<input type="hidden" asp-for="@Model.Lhobby[i].Value" />
<input type="checkbox" class="cb" asp-for="@Model.Lhobby[i].Selected" />@Model.Lhobby[i].Text @:
}
<span asp-validation-for="Lhobby" id="rLhobby" 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" id="rCid" 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" id="rSid" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Iid" class="control-label"></label>
<select asp-for="Iid" multiple style="width:350px" asp-items="Model.Liid" class="form-control"></select>
<span asp-validation-for="Iid" id="rIid" class="text-danger"></span>
</div>
<div class="form-group">
<input type="button" value="Create" id="btnAdd" 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').datepicker();
$('#Doj').prop("type", "");
$('#Iid').multiselect();
$('#btnAdd').click(function () {
$('#reid').text('');
$('#rName').text('');
$('#rAddress').text('');
$('#rPassword').text('');
$('#rCPassword').text('');
$('#rGender').text('');
$('#rDoj').text('');
$('#rSalary').text('');
$('#rEmail').text('');
$('#rIid').text('');
$('#rCid').text('');
$('#rSid').text('');
$('#rLhobby').text('');
if ($('#eid').val() == "") {
$('#reid').text('Eid should not be blank.');
$('#eid').focus();
return;
}
else if ($('#Name').val() == "") {
$('#rName').text('Name should not be blank.');
$('#Name').focus();
return;
}
else if ($('#Address').val() == "") {
$('#rAddress').text('Address should not be blank.');
$('#Address').focus();
return;
}
else if ($('#Password').val() == "") {
$('#rPassword').text('Password should not be blank.');
$('#Password').focus();
return;
}
else if ($('#CPassword').val() == "") {
$('#rCPassword').text('Confirm password should not be blank.');
$('#CPassword').focus();
return;
}
else if ($('#Gender:checked').length==0) {
$('#rGender').text('Please select a gender.');
$('#Gender').focus();
return;
}
else if ($('#Doj').val() =="") {
$('#rDoj').text('Doj should not be blank.');
$('#Doj').focus();
return;
}
else if ($('#Salary').val() == "") {
$('#rSalary').text('Salary should not be blank.');
$('#Salary').focus();
return;
}
else if ($('#Email').val() == "") {
$('#rEmail').text('Email should not be blank.');
$('#Email').focus();
return;
}
else if ($('.cb:checked').length == 0){
$('#rLhobby').text('Please select a hobby.');
return;
}
else if ($('#Cid :selected').text() =="Select") {
$('#rCid').text('Please select a country.');
$('#Cid').focus();
return;
}
else if ($('#Sid :selected').text() == "Select") {
$('#rSid').text('Please select a state.');
$('#Sid').focus();
return;
}
else if ($('#Iid :selected').length == 0) {
$('#rIid').text('Please select a hobby.');
$('#Iid').focus();
return;
}
if ($("form").valid())
$("form").submit();
});
$('#Password').blur(function () {
$('#rPassword').text('');
if ($('#Password').val().length < 6 || $('#Password').val().length > 8) {
$('#rPassword').text('Password length between 6 to 8 charecters long.');
$('#Password').focus();
}
});
$('#CPassword').blur(function () {
$('#rCPassword').text('');
if ($('#CPassword').val()!=$('#Password').val()) {
$('#rCPassword').text('Password and confirm password must be same.');
$('#CPassword').focus();
}
});
$('#Email').blur(function () {
echeck($(this).val());
});
function echeck(str) {
$('#rEmail').text('');
var at = "@@"
var dot = "."
var lat = str.indexOf(at)
var lstr = str.length
var ldot = str.indexOf(dot)
if (str.indexOf(at) == -1) {
$('#rEmail').text('Invalid E-mail ID');
return;
}
if (str.indexOf(at) == -1 || str.indexOf(at) == 0 || str.indexOf(at) == lstr) {
$('#rEmail').text('Invalid E-mail ID');
return;
}
if (str.indexOf(dot) == -1 || str.indexOf(dot) == 0 || str.indexOf(dot) == lstr) {
$('#rEmail').text('Invalid E-mail ID');
return;
}
if (str.indexOf(at, (lat + 1)) != -1) {
$('#rEmail').text('Invalid E-mail ID');
return;
}
if (str.substring(lat - 1, lat) == dot || str.substring(lat + 1, lat + 2) == dot) {
$('#rEmail').text('Invalid E-mail ID');
return;
}
if (str.indexOf(dot, (lat + 2)) == -1) {
$('#rEmail').text('Invalid E-mail ID');
return;
}
if (str.indexOf(" ") != -1) {
$('#rEmail').text('Invalid E-mail ID');
return;
}
}
$('#Salary').keyup(function () {
$('#rSalary').text('');
var m = "0123456789.";
var n = $(this).val();
for (var i = 0; i < n.length; i++)
if (m.indexOf(n.charAt(i)) < 0) {
$('#rSalary').text('You can enter only number.');
$(this).focus();
return;
}
});
$('#Cid').change(function () {
$('#Sid').empty();
$('#Sid').append("<option>Select</option>");
$.ajax({
url: '/Emp/Fillddl',
data: { CID: $(this).val() },
success: function (data) {
$.each(JSON.parse(data), function (i, j) {
$('#Sid').append("<option value='"+j.Sid+"'>"+j.Sname+"</option>");
});
}
});
});
});
</script>
}
Edit View :
@model WebApplication2.Models.EMPVM
@{
ViewData["Title"] = "Edit";
}
<div class="row">
<div class="col-md-4">
<form asp-action="Edit">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<input type="hidden" asp-for="eid" />
<span asp-validation-for="eid" id="reid" 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" id="rName" 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" id="rAddress" 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" id="rGender" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Doj" class="control-label"></label>
<input asp-for="Doj" autocomplete="off" class="form-control" />
<span asp-validation-for="Doj" id="rDoj" 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" id="rSalary" 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" id="rEmail" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Lhobby" class="control-label"></label>
@for (int i = 0; i < Model.Lhobby.Count; i++)
{
<input type="hidden" asp-for="@Model.Lhobby[i].Text" />
<input type="hidden" asp-for="@Model.Lhobby[i].Value" />
<input type="checkbox" class="cb" asp-for="@Model.Lhobby[i].Selected" />@Model.Lhobby[i].Text @:
}
<span asp-validation-for="Lhobby" id="rLhobby" 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" id="rCid" 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" id="rSid" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Iid" class="control-label"></label>
<select asp-for="Iid" multiple style="width:350px" asp-items="Model.Liid" class="form-control"></select>
<span asp-validation-for="Iid" id="rIid" class="text-danger"></span>
</div>
<div class="form-group">
<input type="button" value="Create" id="btnAdd" 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').datepicker();
$('#Doj').prop("type", "");
$('#Iid').multiselect();
$('#btnAdd').click(function () {
$('#reid').text('');
$('#rName').text('');
$('#rAddress').text('');
$('#rGender').text('');
$('#rDoj').text('');
$('#rSalary').text('');
$('#rEmail').text('');
$('#rIid').text('');
$('#rCid').text('');
$('#rSid').text('');
$('#rLhobby').text('');
if ($('#eid').val() == "") {
$('#reid').text('Eid should not be blank.');
$('#eid').focus();
return;
}
else if ($('#Name').val() == "") {
$('#rName').text('Name should not be blank.');
$('#Name').focus();
return;
}
else if ($('#Address').val() == "") {
$('#rAddress').text('Address should not be blank.');
$('#Address').focus();
return;
}
else if ($('#Gender:checked').length==0) {
$('#rGender').text('Please select a gender.');
$('#Gender').focus();
return;
}
else if ($('#Doj').val() =="") {
$('#rDoj').text('Doj should not be blank.');
$('#Doj').focus();
return;
}
else if ($('#Salary').val() == "") {
$('#rSalary').text('Salary should not be blank.');
$('#Salary').focus();
return;
}
else if ($('#Email').val() == "") {
$('#rEmail').text('Email should not be blank.');
$('#Email').focus();
return;
}
else if ($('.cb:checked').length == 0){
$('#rLhobby').text('Please select a hobby.');
return;
}
else if ($('#Cid :selected').text() =="Select") {
$('#rCid').text('Please select a country.');
$('#Cid').focus();
return;
}
else if ($('#Sid :selected').text() == "Select") {
$('#rSid').text('Please select a state.');
$('#Sid').focus();
return;
}
else if ($('#Iid :selected').length == 0) {
$('#rIid').text('Please select a hobby.');
$('#Iid').focus();
return;
}
if ($("form").valid())
$("form").submit();
});
$('#Email').blur(function () {
echeck($(this).val());
});
function echeck(str) {
$('#rEmail').text('');
var at = "@@"
var dot = "."
var lat = str.indexOf(at)
var lstr = str.length
var ldot = str.indexOf(dot)
if (str.indexOf(at) == -1) {
$('#rEmail').text('Invalid E-mail ID');
return;
}
if (str.indexOf(at) == -1 || str.indexOf(at) == 0 || str.indexOf(at) == lstr) {
$('#rEmail').text('Invalid E-mail ID');
return;
}
if (str.indexOf(dot) == -1 || str.indexOf(dot) == 0 || str.indexOf(dot) == lstr) {
$('#rEmail').text('Invalid E-mail ID');
return;
}
if (str.indexOf(at, (lat + 1)) != -1) {
$('#rEmail').text('Invalid E-mail ID');
return;
}
if (str.substring(lat - 1, lat) == dot || str.substring(lat + 1, lat + 2) == dot) {
$('#rEmail').text('Invalid E-mail ID');
return;
}
if (str.indexOf(dot, (lat + 2)) == -1) {
$('#rEmail').text('Invalid E-mail ID');
return;
}
if (str.indexOf(" ") != -1) {
$('#rEmail').text('Invalid E-mail ID');
return;
}
}
$('#Salary').keyup(function () {
$('#rSalary').text('');
var m = "0123456789.";
var n = $(this).val();
for (var i = 0; i < n.length; i++)
if (m.indexOf(n.charAt(i)) < 0) {
$('#rSalary').text('You can enter only number.');
$(this).focus();
return;
}
});
$('#Cid').change(function () {
$('#Sid').empty();
$('#Sid').append("<option>Select</option>");
$.ajax({
url: '/Emp/Fillddl',
data: { CID: $(this).val() },
success: function (data) {
$.each(JSON.parse(data), function (i, j) {
$('#Sid').append("<option value='"+j.Sid+"'>"+j.Sname+"</option>");
});
}
});
});
});
</script>
}
You must add some js & css file for jquery data table & multi select drop down in Layout View .
Layout View :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - WebApplication2</title>
<environment include="Development">
<link rel="stylesheet" href="~/css/site.css" />
<link href="~/jquery-ui-1.12.1.custom/jquery-ui.css" rel="stylesheet" />
<link href="~/DataTables-css/css/jquery.dataTables.css" rel="stylesheet" />
<link href="~/DataTables-css/css/jquery.dataTables_themeroller.css" rel="stylesheet" />
<link href="~/jquery-ui-1.12.1.custom/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">WebApplication2</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 - WebApplication2</p>
</footer>
</div>
<environment include="Development">
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/jquery-ui-1.12.1.custom/jquery-ui.js"></script>
<script src="~/jquery-ui-1.12.1.custom/multiselect.js"></script>
<script src="~/DataTables-js/jquery.dataTables.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.js"></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>