View Model :
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace SMS.ViewModels
{
public class UserroleVM:BaseVM
{
public int URID { get; set; }
public int UID { get; set; }
[Required(ErrorMessage = "Please select user name.")]
[Display(Name = "User Name")]
public string UNAME { get; set; }
[Required(ErrorMessage = "Please select role.")]
[Display(Name = "Role")]
public int RID { get; set; }
public string RNAME { get; set; }
public List<SelectListItem> RLIST { get; set; }
[Required(ErrorMessage = "Please select menu.")]
[Display(Name = "Menu")]
public List<int> MID { get; set; }
public List<SelectListItem> MLIST { get; set; }
public string MNAME { get; set; }
public string PNAME { get; set; }
public List<Pagedetails> PAGELIST { get; set; }
public UserroleVM()
{
RLIST = new List<SelectListItem>();
MID = new List<int>();
MLIST = new List<SelectListItem>();
PAGELIST = new List<Pagedetails>();
}
public void fillddl(List<SelectListItem> rl, List<SelectListItem> ml)
{
RLIST = rl;
MLIST = ml;
}
}
public class Pagedetails
{
public int PID { get; set; }
public string PNAME { get; set; }
public bool ADD { get; set; }
public bool EDIT { get; set; }
public bool DELETE { get; set; }
public bool VIEW { get; set; }
}
}
Controller:
using SMS.Models;
using SMS.ViewModels;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
namespace SMS.Controllers
{
public class UserrolesController : Controller
{
#region variable
private static string message = string.Empty;
#endregion
[HttpGet]
public async Task<ActionResult> Index()
{
using (AppDbContext obj = new AppDbContext())
{
var data1 = await obj.Userroles.ToListAsync();
List<UserroleVM> attendancegrideviews = (from x in data1
join y in obj.Users
on x.UID equals y.UID
join z in obj.Roles
on x.RID equals z.RID
select new UserroleVM()
{
URID = x.RUID,
UNAME = y.UNAME,
RNAME = z.RNAME,
MNAME =string.Join(",", obj.Menus.Where(a => obj.Userrolemenus.Where(p => p.RUID == x.RUID).Select(q => q.MID).Contains(a.MID)).Select(b=>b.MNAME.ToString()).ToList())
}).ToList();
return View(attendancegrideviews);
}
}
[HttpGet]
public async Task<ActionResult> Create()
{
using (AppDbContext obj = new AppDbContext())
{
UserroleVM attendanceVM = new UserroleVM();
attendanceVM.fillddl(await obj.Roles.Select(m => new SelectListItem { Value = m.RID.ToString(), Text = m.RNAME }).ToListAsync(), await obj.Menus.Select(n => new SelectListItem { Value = n.MID.ToString(), Text = n.MNAME }).ToListAsync());
List<Pagedetails> lst = new List<Pagedetails>();
attendanceVM.PAGELIST = lst;
attendanceVM.URID = 0;
if (!string.IsNullOrEmpty(message))
{
attendanceVM.Message = message;
message = null;
}
return View(attendanceVM);
}
}
[HttpPost]
[ValidateAntiForgeryToken()]
public async Task<ActionResult> Create(UserroleVM attendanceVM)
{
if (ModelState.IsValid)
{
using (AppDbContext obj = new AppDbContext())
{
Userrole incomehead = new Userrole();
if (attendanceVM.URID == 0)
{
incomehead.UID = attendanceVM.UID;
incomehead.RID = attendanceVM.RID;
obj.Entry(incomehead).State = EntityState.Added;
await obj.SaveChangesAsync();
obj.Userrolemenus.AddRange(attendanceVM.MID.Select(x=>new Userrolemenu { RUID=incomehead.RUID, MID=x }));
await obj.SaveChangesAsync();
obj.Userrolepages.AddRange(attendanceVM.PAGELIST.Select(x => new Userrolepage { RUID = incomehead.RUID, PID=x.PID,ADD=x.ADD, EDIT=x.EDIT, DELETE=x.DELETE, VIEW=x.VIEW }));
await obj.SaveChangesAsync();
message = "Data Saved Successfully.";
}
else
{
incomehead = obj.Userroles.Find(attendanceVM.URID);
incomehead.UID = attendanceVM.UID;
incomehead.RID = attendanceVM.RID;
obj.Entry(incomehead).State = EntityState.Modified;
await obj.SaveChangesAsync();
obj.Userrolemenus.RemoveRange(obj.Userrolemenus.Where(x=>x.RUID==incomehead.RUID));
await obj.SaveChangesAsync();
obj.Userrolemenus.AddRange(attendanceVM.MID.Select(x => new Userrolemenu { RUID = incomehead.RUID, MID = x }));
await obj.SaveChangesAsync();
obj.Userrolepages.RemoveRange(obj.Userrolepages.Where(x => x.RUID == incomehead.RUID));
await obj.SaveChangesAsync();
obj.Userrolepages.AddRange(attendanceVM.PAGELIST.Select(x => new Userrolepage { RUID = incomehead.RUID, PID = x.PID, ADD = x.ADD, EDIT = x.EDIT, DELETE = x.DELETE, VIEW = x.VIEW }));
await obj.SaveChangesAsync();
message = "Data Updated Successfully.";
}
return RedirectToAction("Create");
}
}
return View(attendanceVM);
}
[HttpPost]
public async Task<ActionResult> Create1(UserroleVM attendanceVM)
{
using (AppDbContext obj = new AppDbContext())
{
List<Pagedetails> lst =await (from m in obj.Pages.Where(p=>attendanceVM.MID.Contains(p.MID))
select new Pagedetails {PID=m.PID, PNAME=m.PNAME}).ToListAsync();
attendanceVM.PAGELIST = lst;
attendanceVM.UID = attendanceVM.UID;
attendanceVM.UNAME = attendanceVM.UNAME;
attendanceVM.fillddl(await obj.Roles.Select(m => new SelectListItem { Value = m.RID.ToString(), Text = m.RNAME }).ToListAsync(), await obj.Menus.Select(n => new SelectListItem { Value = n.MID.ToString(), Text = n.MNAME }).ToListAsync());
attendanceVM.RID = attendanceVM.RID;
attendanceVM.MID = attendanceVM.MID;
attendanceVM.URID = attendanceVM.URID;
return View("Create", attendanceVM);
}
}
[HttpGet]
public async Task<ActionResult> Edit(int id)
{
using (AppDbContext obj = new AppDbContext())
{
UserroleVM attendanceVM = new UserroleVM();
Userrole av = obj.Userroles.Find(id);
attendanceVM.UID = av.UID;
attendanceVM.UNAME = obj.Users.SingleOrDefault(m=>m.UID==av.UID).UNAME;
attendanceVM.fillddl(await obj.Roles.Select(m => new SelectListItem { Value = m.RID.ToString(), Text = m.RNAME }).ToListAsync(), await obj.Menus.Select(n => new SelectListItem { Value = n.MID.ToString(), Text = n.MNAME }).ToListAsync());
attendanceVM.RID = av.RID;
attendanceVM.MID = obj.Userrolemenus.Where(p => p.RUID == av.RUID).Select(x => x.MID).ToList();
attendanceVM.URID = av.RUID;
List<Pagedetails> lst = await (from m in obj.Pages.Where(p => attendanceVM.MID.Contains(p.MID))
join n in obj.Userrolepages
on m.PID equals n.PID
select new Pagedetails { PID = m.PID, PNAME = m.PNAME, ADD=n.ADD,EDIT=n.EDIT,DELETE=n.DELETE,VIEW=n.VIEW }).ToListAsync();
attendanceVM.PAGELIST = lst;
return View("Create", attendanceVM);
}
}
[HttpGet]
public async Task<ActionResult> Delete(int id)
{
using (AppDbContext obj = new AppDbContext())
{
Userrole addmission = obj.Userroles.Find(id);
obj.Entry(addmission).State = EntityState.Deleted;
await obj.SaveChangesAsync();
obj.Userrolemenus.RemoveRange(obj.Userrolemenus.Where(x => x.RUID == id));
await obj.SaveChangesAsync();
obj.Userrolepages.RemoveRange(obj.Userrolepages.Where(x => x.RUID == id));
await obj.SaveChangesAsync();
return RedirectToAction("Index");
}
}
public async Task<PartialViewResult> Details(int id)
{
using (AppDbContext obj = new AppDbContext())
{
var data1 = await obj.Userroles.Where(m=>m.RUID==id).ToListAsync();
UserroleVM attendancegrideviews = (from x in data1
join y in obj.Users
on x.UID equals y.UID
join z in obj.Roles
on x.RID equals z.RID
select new UserroleVM()
{
URID = x.RUID,
UNAME = y.UNAME,
RNAME = z.RNAME,
MNAME = string.Join(",", obj.Menus.Where(a => obj.Userrolemenus.Where(p => p.RUID == x.RUID).Select(q => q.MID).Contains(a.MID)).Select(b => b.MNAME.ToString()).ToList()),
PAGELIST = obj.Userrolepages.Where(g => g.RUID == x.RUID).Select(h => new Pagedetails
{
PNAME = obj.Pages.FirstOrDefault(i => i.PID == h.PID).PNAME,
ADD = h.ADD,
EDIT = h.EDIT,
DELETE = h.DELETE,
VIEW = h.VIEW
}).ToList()
}).FirstOrDefault(m=>m.URID==id);
return PartialView("DetailsPV", attendancegrideviews);
}
}
[HttpPost]
public ActionResult AutoComplete(string prefix)
{
using (AppDbContext obj = new AppDbContext())
{
return Json(obj.Users.Select(x => new { val = x.UID, label = x.UNAME }).ToList(), JsonRequestBehavior.AllowGet);
}
}
}
}
Index View :
@model IEnumerable<SMS.ViewModels.UserroleVM>
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Adminlayout.cshtml";
}
<p>
@Html.ActionLink("Add New", "Create", null, new { @class = "btn btn-primary" })
</p>
<table class="table table-bordered table-hover table-responsive" id="tbc">
<thead class="bg bg-primary">
<tr>
<th>
ID
</th>
<th>
User Name
</th>
<th>
Role Name
</th>
<th>
Menus Name
</th>
<th>Action</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.URID)
</td>
<td>
@Html.DisplayFor(modelItem => item.UNAME)
</td>
<td>
@Html.DisplayFor(modelItem => item.RNAME)
</td>
<td>
@Html.DisplayFor(modelItem => item.MNAME)
</td>
<td>
<a href="#"><span class="glyphicon glyphicon-eye-open view"></span></a> |
<a href="@Url.Action("Edit","Userroles",new {id=item.URID })"><span class="glyphicon glyphicon-edit edit"></span></a> |
<a href="#" onclick="confirmDelete('@Url.Content("~/Userroles/Delete/" + item.URID)')"><span class="glyphicon glyphicon-remove-circle del"></span></a>
</td>
</tr>
}
</tbody>
</table>
@Html.Partial("DeletePV")
<div class="modal fade" id="deleteModal1" data-keyboard="false" data-backdrop="static" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="myModalLabel">User Access Details</h4>
</div>
<div class="modal-body bd">
</div>
<div class="modal-footer">
<input type="button" value="Close" class="btn btn-primary focusedButton" data-dismiss="modal" style="width:80px" />
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(function () {
var table = $("#tbc").DataTable({
"order": [[0, "asc"]],
"lengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
"scroller": true,
"orderClasses": false,
});
$('.view').click(function () {
var Id = $(this).closest("tr").find("td:first").text();
$.ajax({
"url": '@Url.Action("Details", "Userroles")',
type: 'Get',
datatype: 'json',
cache: false,
async: true,
data: {id:Id},
success: function (data) {
$('#deleteModal1').find('.bd').empty().append(data);
$('#deleteModal1').modal('show');
},
error: function (t) {
alert(t.responseText);
}
});
});
});
</script>
Create View :
@model SMS.ViewModels.UserroleVM
@{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Adminlayout.cshtml";
}
<style>
.top-buffer {
margin-top: 2px;
}
</style>
<h2>User Access Details</h2><br />
@using (Html.BeginForm("Create", "Userroles"))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="row">
<div class="col-md-2 col-sm-2 col-lg-2 col-xl-2">
@Html.LabelFor(model => model.UNAME, htmlAttributes: new { @class = "control-label ", @autocomplete = "off" })
</div>
<div class="col-md-4 col-sm-4 col-lg-4 col-xl-4">
@Html.HiddenFor(m => m.UID)
@Html.HiddenFor(m => m.URID)
@Html.EditorFor(model => model.UNAME, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.UNAME, "", new { @class = "text-danger" })
</div>
<div class="col-md-2 col-sm-2 col-lg-2 col-xl-2">
@Html.LabelFor(model => model.RID, htmlAttributes: new { @class = "control-label " })
</div>
<div class="col-md-4 col-sm-4 col-lg-4 col-xl-4">
@Html.DropDownListFor(model => model.RID, Model.RLIST, "Select", new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.RID, "", new { @class = "text-danger" })
</div>
</div>
<div class="row top-buffer">
<div class="col-md-2 col-sm-2 col-lg-2 col-xl-2">
@Html.LabelFor(model => model.MID, htmlAttributes: new { @class = "control-label " })
</div>
<div class="col-md-4 col-sm-4 col-lg-4 col-xl-4">
@Html.ListBoxFor(model => model.MID, Model.MLIST, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.MID, "", new { @class = "text-danger" })
</div>
<div class="col-md-2 col-sm-2 col-lg-2 col-xl-2">
<input type="button" value="Display" class="btn btn-primary" style="width:80px" id="btnd" />
</div>
</div>
<div class="row top-buffer" style="overflow:auto; height:550px; border:#808080 1px solid">
<table class="table table-bordered table-hover table-responsive" id="tbuser">
<thead class="bg bg-primary">
<tr>
<th>
Page Name
</th>
<th>
Add
</th>
<th>
Edit
</th>
<th>
Delete
</th>
<th>
View
</th>
</tr>
</thead>
<tbody>
@{
if (Model.PAGELIST.Count == 0)
{
<tr><td colspan="5" style="text-align:center">No data available in table</td></tr>
}
for (int i = 0; i < Model.PAGELIST.Count; i++)
{
<tr>
<td>
@Html.HiddenFor(modelItem => Model.PAGELIST[i].PID)
@Html.DisplayFor(modelItem => Model.PAGELIST[i].PNAME)
@Html.HiddenFor(modelItem => Model.PAGELIST[i].PNAME)
</td>
<td style="text-align:center">
@Html.CheckBoxFor(modelItem => Model.PAGELIST[i].ADD, htmlAttributes: new { @class = "cbAdd" })
</td>
<td style="text-align:center">
@Html.CheckBoxFor(modelItem => Model.PAGELIST[i].EDIT, htmlAttributes: new { @class = "cbEdit" })
</td>
<td style="text-align:center">
@Html.CheckBoxFor(modelItem => Model.PAGELIST[i].DELETE, htmlAttributes: new { @class = "cbDelete" })
</td>
<td style="text-align:center">
@Html.CheckBoxFor(modelItem => Model.PAGELIST[i].VIEW, htmlAttributes: new { @class = "cbView" })
</td>
</tr>
}
}
</tbody>
</table>
</div>
<div class="row top-buffer col-md-12 col-sm-12 col-lg-12 col-xl-12">
<div class="col-md-6 col-sm-6 col-lg-6 col-xl-6"> </div>
<div class="col-md-6 col-sm-6 col-lg-6 col-xl-6 pull-right">
<input type="button" id="btns" value="Submit" class="btn btn-primary" style="width:80px" />
@{
if (Model.URID == 0)
{
@Html.ActionLink("Reset", "Create", null, new { @class = "btn btn-default", @style = "width:80px" })
}
else
{
@Html.ActionLink("Reset", "Edit", new { id = Model.URID }, new { @class = "btn btn-default", @style = "width:80px" })
}
}
</div>
</div>
</div>
}
@{
if (@Model.Message != null && @Model != null)
{
@Html.Partial("AlertPV", new SMS.ViewModels.Success() { Alertmessage = Model.Message })
}
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
<div class="modal fade" id="successModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" id="btnclose" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="myModalLabel">Alert Message</h4>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" id="btnOk" class="btn btn-primary focusedButton" data-dismiss="modal">Ok</button>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(function () {
$('#MID').chosen();
$('#btnd').click(function () {
if ($("form").valid()) {
$.ajax({
type: 'Post',
datatype: 'json',
cache: false,
async: true,
beforeSend: function () {
HoldOn.open({ theme: "sk-rect", content: '', message: 'Please wait for some time ...', backgroundColor: "#8C8C8C", textColor: "white" });
$("form").attr("action", "@Url.Action("Create1","Userroles")");
$("form").submit();
},
complete: function () {
HoldOn.close();
},
error: function (a, b, c) {
HoldOn.close();
}
});
}
});
$('#btns').click(function () {
if ($("form").valid()) {
$.ajax({
type: 'Post',
datatype: 'json',
cache: false,
async: true,
beforeSend: function () {
HoldOn.open({ theme: "sk-rect", content: '', message: 'Please wait for some time ...', backgroundColor: "#8C8C8C", textColor: "white" });
$("form").submit();
},
complete: function () {
HoldOn.close();
},
error: function (a, b, c) {
HoldOn.close();
}
});
}
});
$('#btnOk,#btnclose').click(function () {
var id =@Html.Raw(Json.Encode(Model.URID));
if (id == 0) {
window.location.href = "Index";
} else {
window.location.href = 0;
}
});
var url = '@Url.Action("AutoComplete", "Userroles")';
$('#UNAME').typeahead({
hint: true,
highlight: true,
minLength: 1,
source: function (request, response) {
$.ajax({
url: url,
//data: "{ 'prefix': '" + request + "'}",
data: { prefix: request },
dataType: "json",
type: "POST",
//contentType: "application/json; charset=utf-8",
success: function (data) {
//var data = JSON.parse(data1);
//console.log(data);
items = [];
map = {};
$.each(data, function (i, item) {
var id = item.val;
var name = item.label;
map[name] = { id: id, name: name };
items.push(name);
//items.push(item.name);
});
response(items);
$(".dropdown-menu").css("height", "auto");
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
updater: function (item) {
$('#UID').val(map[item].id);
return item;
}
});
});
</script>
Details View :
@model SMS.ViewModels.UserroleVM
<div class="row">
<div class="col-md-1 col-sm-1 col-lg-1 col-xl-1"><b>User:</b></div><div class="col-md-3 col-sm-3 col-lg-3 col-xl-3">@Model.UNAME</div>
<div class="col-md-1 col-sm-1 col-lg-1 col-xl-1"><b>Roles:</b></div><div class="col-md-2 col-sm-2 col-lg-2 col-xl-2"> @Model.RNAME</div>
<div class="col-md-1 col-sm-1 col-lg-1 col-xl-1"><b>Menus:</b></div><div class="col-md-4 col-sm-4 col-lg-4 col-xl-4">@Model.MNAME</div>
</div><br />
<div class="row">
<table class="table table-bordered table-hover table-responsive" id="tbc123" >
<thead class="bg bg-primary">
<tr>
<th>Page Name</th>
<th>Add</th>
<th>Edit</th>
<th>Delete</th>
<th>View</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model.PAGELIST)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.PNAME)
</td>
<td>
@Html.DisplayFor(modelItem => item.ADD)
</td>
<td>
@Html.DisplayFor(modelItem => item.EDIT)
</td>
<td>
@Html.DisplayFor(modelItem => item.DELETE)
</td>
<td>
@Html.DisplayFor(modelItem => item.VIEW)
</td>
</tr>
}
</tbody>
</table>
</div>
<script type="text/javascript">
$(function () {
var table = $("#tbc123").DataTable({
"order": [[0, "asc"]],
"lengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
"scroller": true,
"orderClasses": false,
});
});
</script>
Thank you this was a nice blog. For technologies Java Projects With Source Code on Takeoff Edu Group.
ReplyDelete