Remember selected checkboxes across paginated pages - asp.net-mvc-4

I am displaying data in a table and doing some paging and sorting. I have a checkbox for everyrow.
When I move from one page to another, I will like to keep the checkboxes checked if they were checked.
I dont want the checked boxes to uncheck as I navigate from page to page. How do i achieve that?
Here is my jquery.
<script type="text/javascript">
$(document).ready(function () {
$(".header").click(function (evt) {
var sortfield = $(evt.target).data("sortfield");
if ($("#SortField").val() == sortfield)
{
if($("#SortDirection").val()=="ascending")
{
$("#SortDirection").val("descending");
}
else
{
$("#SortDirection").val("ascending");
}
}
else
{
$("#SortField").val(sortfield);
$("#SortDirection").val("ascending");
}
evt.preventDefault();
$("form").submit();
});
$(".pager").click(function (evt) {
var pageindex = $(evt.target).data("pageindex");
$("#CurrentPageIndex").val(pageindex);
evt.preventDefault();
$("form").submit();
});
});
</script>
Here is my html page
<body>
<h1>List of Customers</h1>
#{
PageSortOnlineEx.Models.SortingPagingInfo info = ViewBag.SortingPagingInfo;
}
#using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
#Html.Hidden("SortField", info.SortField)
#Html.Hidden("SortDirection", info.SortDirection)
#Html.Hidden("PageCount", info.PageCount)
#Html.Hidden("PageSize", info.PageSize)
#Html.Hidden("CurrentPageIndex", info.CurrentPageIndex)
<table border="1" cellpadding="10">
<tr>
<th>Select</th>
<th>CustomerID</th>
<th>CompanyName</th>
<th>ContactName</th>
<th>Country</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>#Html.CheckBox("select", false)</td>
<td>#item.CustomerID</td>
<td>#item.CompanyName</td>
<td>#item.ContactName</td>
<td>#item.Country</td>
</tr>
}
<tr>
<td colspan="4">
#for (var i = 0; i < info.PageCount; i++)
{
if (i == info.CurrentPageIndex)
{
<span>#(i + 1)</span>
}
else
{
#(i + 1)
}
}
</td>
</tr>
</table>
}
</body>
Here is my controller code
public ActionResult Index()
{
using (NorthwindEntities db = new NorthwindEntities())
{
SortingPagingInfo info = new SortingPagingInfo();
info.SortField = "CustomerID";
info.SortDirection = "ascending";
info.PageSize = 10;
info.PageCount = Convert.ToInt32(Math.Ceiling((double)(db.Customers.Count() / info.PageSize)));
info.CurrentPageIndex = 0;
var query = db.Customers.OrderBy(c => c.CustomerID).Take(info.PageSize);
ViewBag.SortingPagingInfo = info;
List<Customer> model = query.ToList();
return View(model);
}
}
[HttpPost]
public ActionResult Index(SortingPagingInfo info)
{
using (NorthwindEntities db = new NorthwindEntities())
{
IQueryable<Customer> query = null;
switch (info.SortField)
{
case "CustomerID":
query = (info.SortDirection == "ascending" ? db.Customers.OrderBy(c => c.CustomerID) : db.Customers.OrderByDescending(c => c.CustomerID));
break;
case "CompanyName":
query = (info.SortDirection == "ascending" ? db.Customers.OrderBy(c => c.CompanyName) : db.Customers.OrderByDescending(c => c.CompanyName));
break;
case "ContactName":
query = (info.SortDirection == "ascending" ? db.Customers.OrderBy(c => c.ContactName) : db.Customers.OrderByDescending(c => c.ContactName));
break;
case "Country":
query = (info.SortDirection == "ascending" ? db.Customers.OrderBy(c => c.Country) : db.Customers.OrderByDescending(c => c.Country));
break;
}
query = query.Skip(info.CurrentPageIndex * info.PageSize).Take(info.PageSize);
ViewBag.SortingPagingInfo = info;
List<Customer> model = query.ToList();
return View(model);
}
}

Related

Records Not Displaying in jquery.datatables using server side pagination processing

i am trying to get jquery.datatables working using server side processing and pagination. I used the following example article as a guide because its close to the version VS2017 that i am using-
https://www.c-sharpcorner.com/article/filtering-jquery-data-table-server-side-using-mvc-and-entity-framework/
When I run the application i get the following error:
DataTables warning: table id=tblrtr - Requested unknown parameter 'Id' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4
and an empty grid that shows 10 blank lines and the right page count.
I have debugged the code and it finds all the records and values, and indeed the finalresult variable does return the contents of the 10 rows- but they dont seem to make it to the datatable grid.
Here is the controller code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using RTMGMTTest.Models;
namespace RTMGMTTest.Controllers
{
public class ReportsToRecordsController : Controller
{
private readonly RTMGMTContext _context;
public ReportsToRecordsController(RTMGMTContext context)
{
_context = context;
}
// GET: ReportsToRecords
public async Task<IActionResult> Index()
{
//return View(await _context.ReportsToRecords.ToListAsync());
return View();
}
[HttpPost]
public JsonResult RTRList(DTParameters param)
{
int TotalCount = 0;
var filtered = this.GetRTRFiltered(param.Search.Value, param.SortOrder, param.Start, param.Length, out TotalCount);
var RTRList = filtered.Select(o => new ReportsToRecords()
{
Id = o.Id,
ReportingId = o.ReportingId,
Title = o.Title,
Name = o.Name,
ReportsToId = o.ReportsToId,
EmployeeId = o.EmployeeId
});
DTResult<ReportsToRecords> finalresult = new DTResult<ReportsToRecords>
{
draw = param.Draw,
data = RTRList.ToList(),
recordsFiltered = TotalCount,
recordsTotal = filtered.Count
};
return Json(finalresult);
}
and
//for server side processing
public List<ReportsToRecords> GetRTRFiltered(string search, string sortOrder, int start, int length, out int TotalCount)
{
var result = _context.ReportsToRecords.Where(p => (search == null
|| (p.ReportingId != null && p.ReportingId.ToLower().Contains(search.ToLower())
|| p.Title != null && p.Title.ToLower().Contains(search.ToLower())
|| p.Name != null && p.Name.ToLower().Contains(search.ToLower())
|| p.ReportsToId != null && p.ReportsToId.ToLower().Contains(search.ToLower())
|| p.EmployeeId!= null && p.EmployeeId.ToLower().Contains(search.ToLower())
))).ToList();
TotalCount = result.Count;
result = result.Skip(start).Take(length).ToList();
switch (sortOrder)
{
case "ReportingId":
result = result.OrderBy(a => a.ReportingId).ToList();
break;
case "Title":
result = result.OrderBy(a => a.Title).ToList();
break;
case "Name":
result = result.OrderBy(a => a.Name).ToList();
break;
case "ReportsToId":
result = result.OrderBy(a => a.ReportsToId).ToList();
break;
case "EmployeeId":
result = result.OrderBy(a => a.EmployeeId).ToList();
break;
default:
result = result.AsQueryable().ToList();
break;
}
return result.ToList();
}
The view page looks as follows:
#model IEnumerable<RTMGMTTest.Models.ReportsToRecords>
#{
ViewData["Title"] = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
<p>
<a asp-action="Create">Create New</a>
</p>
<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.3.1.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" />
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function () {
if ($.fn.DataTable.isDataTable('#tblrtr')) {
$('#tblrtr').dataTable().fnDestroy();
$('#tblrtr').dataTable().empty();
}
var complete = $('#tblrtr').DataTable(
{
"serverSide": true,
"destroy": true,
"processing": true,
"ajax":
{
url: "/ReportsToRecords/RTRList",
method: "POST"
},
"columns": [
{ "data": "Id"},
{ "data": "ReportingId" },
{ "data": "Title" },
{ "data": "Name" },
{ "data": "ReportsToId" },
{ "data": "EmployeeId" }
]
}
);
/// Following code is for filter input to apply filter only on Enter
var itm = $("#tblrtr_filter input")
itm.unbind();
itm.keyup(function (e) {
//enter or tab
if (e.keyCode == 13) {
complete.search(this.value).draw();
}
});
});
</script>
<table class="table" id="tblrtr">
<thead>
<tr>
<th>
Id
</th>
<th>
ReportingId
</th>
<th>
Title
</th>
<th>
Name
</th>
<th>
ReportsToId
</th>
<th>
EmployeeId
</th>
<th></th>
</tr>
</thead>
<tbody></tbody>
</table>
Does anyone know what would cause the data returned from the controller to not display and cause the resulting message? Thanks.

Data not binding to Kendo dropdown list in mvc4

Data is not binding to Kendo dropdown list list is returning form my method
My dropdown
#(Html.Kendo().DropDownListFor(model => model.ParentAssetID)
.OptionLabel(" ")
.Name("ParentAssetID")
.DataTextField("AssetName")
.DataValueField("AssetId")
.SelectedIndex(0)
.Text(string.Empty)
.DataSource(source =>
{
source.Read(read =>
{
read.Url("../Asset/GetAllAssetsByCompanyId");
});
}))
my Action Result
public IEnumerable<AssetDetails> GetAllAssetsByCompanyId()
{
IList<AssetDetails> _assetSearchlist;
using (var client = new HttpClient())
{
AssetRepository assetrep = new AssetRepository();
Guid cp = new Guid(Session["CurrentCompanyId"].ToString());
_assetSearchlist = assetrep.GetAllAssetsByCompanyId(cp, "", "", "");
return _assetSearchlist;
}
}
public JsonResult GetOpportunityListByAccount(string Id)
{
Guid ID = new Guid(Id);
List<OpportunityViewModel> cpvm = new List<OpportunityViewModel>();
List<CrmOpportunity> crmOppList = new List<CrmOpportunity>();
cpvm = srv.OpportunitySet.Where(z => z.CustomerId.Id == ID).ToList();
foreach (var crm in cpvm )
{
CrmOpportunity crmOpp = new CrmOpportunity();
crmOpp.Id = crm.Id;
crmOpp.Name = crm.Name;
crmOppList.Add(crmOpp);
}
return Json(crmOppList, JsonRequestBehavior.AllowGet);
}
#(Html.Kendo().DropDownListFor(x => x.FromOpportunity)
.Name("OpportunityDDL")
.DataTextField("Name")
.DataValueField("Id")
.DataSource(source => {
source.Read(read =>
{
read.Action("GetOpportunityListByAccount", "CrmIntegration");
})
. ServerFiltering(true);
})
.HtmlAttributes( new { style = "margin-left:13px; width: 275px;" })
)
Data access is a little truncated but this is what you'll need to do
#(Html.Kendo().DropDownListFor(model => model.ParentAssetID)
.OptionLabel(" ")
.Name("ParentAssetID")
.DataTextField("AssetName")
.DataValueField("AssetId")
.SelectedIndex(0)
.Text(string.Empty)
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetAllAssetsByCompanyId", "Asset");
});
}))
Only a minor change but have you tried read.Action? Also is maybe try removing the following;
DropDownListFor(model => model.ParentAssetID)
and replace with
DropDownListFor<ClassName>()
Only a thought.

how to Filter webgrid in mvc4 based on textbox input and dropdownList input

I am still in learning curve of mvc4 . I know how to bind a webgrid in mvc4 . But my doubt is can anyone share me the idea how to bind webgrid based on filter conditions from textbox input and dropdownList input. For eg : If textbox has a date "11/15/2013" and dropdownList has the doctor name "Charles" then i need to show in gridview the list of patients who has appointment with doctor " charles " on "11/15/2013" .
code
<div id="gridContent">
#grid.GetHtml(
fillEmptyRows: true,
tableStyle: "webGrid",
alternatingRowStyle: "alternate-row",
headerStyle: "grid-header",
footerStyle: "grid-footer",
mode: WebGridPagerModes.All,
firstText: "<< First",
previousText: "< Prev",
nextText: "Next >",
lastText: "Last >>",
columns: new[] {
grid.Column("PatientID"),
grid.Column("PatientName"),
grid.Column("Age"),
grid.Column("DOB"),
grid.Column("Sex"),
grid.Column("Phone"),
grid.Column("Mobile"),
grid.Column("City"),
grid.Column("PinCode"),
// grid.Column("Dr_Remarks",header:"Remarks",style:"left"),
//grid.Column("Dr_Add1",
// header: "Bed Count",style:"right"
//),
grid.Column("",
header: "Actions",
format: #<text>
#Html.ActionLink("Edit", "EditPatient", new { id = item.PatientID }, htmlAttributes: new { #class = "link" })
|
#Html.ActionLink("Delete", "PatientList", new { id = item.PatientID },
htmlAttributes: new { #class = "link", onclick = "return confirm('Are you sure you wish to delete this record?');" })
</text>
)
})
</div>
**controller**
public ActionResult PatientList(int page = 1, string sort = "Dr_Id", string sortDir = "ASC", int id = 0)
{
if (id != 0)
{
bool isDelete = false;
isDelete = rdm_Patient.DeletePatient(id);
return View(GetPatient(page, sort, sortDir));
}
else
{
return View(GetPatient(page, sort, sortDir));
}
}
private PatientPageViewModel GetPatient(int page = 1, string sort = "Dr_Id", string sortDir = "ASC")
{
const int patientPerPage = 5;
var numPatient = rdm_Patient.CountPatient();
sortDir = sortDir.Equals("desc", StringComparison.CurrentCultureIgnoreCase) ? sortDir : "asc";
var validColumns = new[] { "PatientID", "PatientName" };
if (!validColumns.Any(c => c.Equals(sort, StringComparison.CurrentCultureIgnoreCase)))
sort = "PatientID";
var doctors = rdm_Patient.getpatientpage(page, patientPerPage, "it." + sort + " " + sortDir);
var data = new PatientPageViewModel()
{
numberOfPatient = numPatient,
patientPerPage = patientPerPage,
Patient = doctors,
};
return data;
}
As I understand of your question you need filtering in your WebGrid that doesn’t include any kind of tool to perform it. So, you have to do it manually.
You should take into account the following points:
Firstly, include a form in the View where the query criteria is collected in order to send it to the controller.
Secondly, prepare the Controller so it can receive this criteria and make it reach the Model.
Thirdly, in the Model, simply apply this criteria when counting the total amount of rows, and when obtaining the data to be displayed in the grid page.
Jose M. Aguilar in his post describes all steps which can help you to design your view and controller.
Index.cshtml:
#model MvcApplication1.Models.Employee
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<table>
<tr>
<td>
#Html.DropDownList("lstdepartment", Model.Department_List)
</td>
</tr>
<tr>
<td>
<div id="EmployeeViewGrid">
#Html.Partial("EmployeeView",Model.Employee_Grid)
</div>
</td>
</tr>
</table>
<script type="text/javascript">
$('#lstdepartment').change(function (e) {
e.preventDefault();
var url = '#Url.Action("Filter")';
$.get(url, { department: $(this).val() }, function (result) {
debugger;
$('#EmployeeViewGrid').html(result);
});
});
</script>
Partial view:
#model List< MvcApplication1.Models.Employee>
#{
ViewBag.Title = "EmployeeView";
}
<h2>EmployeeView</h2>
<div id="gridposition" style="overflow: scroll; height: 300px; overflow-x: hidden;">
#{
var grid1 = new WebGrid(source: Model, canPage: true, rowsPerPage: 5, ajaxUpdateContainerId: "gridContent");
#grid1.GetHtml(mode: WebGridPagerModes.All, tableStyle: "webGrid",
headerStyle: "header",
alternatingRowStyle: "alt",
selectedRowStyle: "select",
rowStyle: "description",
htmlAttributes: new { id = "positionGrid" },
fillEmptyRows: false,
columns: grid1.Columns(
grid1.Column("EmployeeId", header: "EmployeeId"),
grid1.Column("EmpName", header: "EmpName"),
grid1.Column("Age", header: "Age"),
grid1.Column("Department", header: "Department"),
grid1.Column("Salary", header: "Salary")))
}
</div>
Controller:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication1.Models;
namespace MvcApplication1.Controllers
{
public class EmployeeController : Controller
{
private EmployeeDatabaseEntities1 db = new EmployeeDatabaseEntities1();
//
// GET: /Employee/
public ActionResult Index()
{
Employee _model = new Employee();
//_model.Employee_Grid = db.tbl_Employee.ToList();
var departmentlist = db.tbl_department.ToList();
_model.Department_List = (from d in departmentlist
select new SelectListItem
{
Value = d.department_id.ToString(),
Text = d.department_name
}).ToList();
var qq = (from e in db.tbl_Employee
join d in db.tbl_department on e.Department_id equals d.department_id
select new Employee
{
Department_id=e.Department_id,
EmployeeId=e.EmployeeId,
EmpName=e.EmpName,
Age=e.Age,
Department=d.department_name
}).ToList();
_model.Employee_Grid = qq;
return View("Index", _model);
}
public ActionResult Filter(string department)
{
int? department_id = Convert.ToInt32(department);
var qq = (from e in db.tbl_Employee
join d in db.tbl_department on e.Department_id equals d.department_id
where e.Department_id == department_id
select new Employee
{
Department_id = e.Department_id,
EmployeeId = e.EmployeeId,enter code here
EmpName = e.EmpName,
Age = e.Age,
Department = d.department_name
}).ToList();
return PartialView("EmployeeView",qq);
}
}
}

How to use href attribute in mvc4

I am having a < href > attributes in my .cshtml page at mvc4 #cp.Name
in my mvc 4 .... what i need is if a person clicks the above link . i have to redirect him to any of the ActionName in Controller (for eg: Index in HomeController )...... how to do it. In my above sample i have redirected to google.com...... but i need to redirect to any of actionname in controller......
My code:
<nav> #{ List<MenuRazor.Models.MenuItem> menulist = ViewBag.Menu; }
<ul id="menu">
#foreach (var mp in menulist.Where(p => p.ParentMenu_Id == 0)) {
<li> #mp.Name
#if (menulist.Count(p => p.ParentMenu_Id == mp.Id) > 0)
{ #:<ul> }
#RenderMenuItem(menulist, mp)
#if (menulist.Count(p => p.ParentMenu_Id == mp.Id) > 0){#:</ul> }
</li> }
</ul>
#helper RenderMenuItem(List<MenuRazor.Models.MenuItem> menuList, MenuRazor.Models.MenuItem mi)
{
foreach (var cp in menuList.Where(p => p.ParentMenu_Id == mi.Id)) {
#:<li> #cp.Name
if (menuList.Count(p => p.ParentMenu_Id == cp.Id) > 0) {
#:<ul>
}
#RenderMenuItem(menuList, cp)
if (menuList.Count(p => p.ParentMenu_Id == cp.Id) > 0) {
#:</ul>
} else {
#:</li>
}
} } </nav>
You can use: #Url.Action("ActionName", "ControllerName")
Refer this MSDN link for more information.
You can use #Html.ActionLink or #Url.Action to generated you link.
#Html.ActionLink("Link name", "Action", "Controller", new { id = your_param }, null)
or
#Url.Action("Action", "Controller")
The #Html.ActionLink might better suit your current problem.

Banking API queried by Javascript

I am finalising a college project and I am stuck.
I have created an API in netbeans and it is working fine.
Returing e.g.
<?xml version="1.0" encoding="UTF-8"?>
<accountholder>
<accountnumber>45672</accountnumber>
<address>234 THE BANK, DUBLIN 1</address>
<balance>763.32</balance>
<email>JOHANN#SMITH.COM</email>
<firstname>JOHANN</firstname>
<id>1</id>
<lastname>SMITH</lastname>
<pinnumber>1234</pinnumber>
</accountholder>
Now I am trying to create a javascript to return data when searching by Id.
<script language="javascript" type="text/javascript">
var request = null;
function createRequest() {
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject("MsXML2.XMLHTTP");
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = null;
}
}
}
if (request == null)
alert("Error creating request object!");
}
function getMessage()
{
createRequest();
var accountholderid = document.getElementById("Id").value;
id=eval(accountholderid);
var url = "http://localhost:8080/BankProjectApi/webresources/bankprojectapi.accountholder/"+id;
request.onreadystatechange = handleResponse;
request.open("GET", url, true);
request.send(null);
}
function handleResponse() {
if (request.readyState==4 && request.status==200)
{
var xmlDocument=request.responseXML;
var firstname = xmlDocument.getElementsByTagName("firstname");
var lastname = xmlDocument.getElementsByTagName("lastname");
var accountnumber = xmlDocument.getElementsByTagName("accountnumber");
for(var i=0; i<firstname.length; i++) {
var firstname = firstname[i].childNodes[0].nodeValue;
var lastname = lastname[i].childNodes[0].nodeValue;
var accountnumber= accountnumber[i].childNodes[0].nodeValue;
document.getElementById('lastname').value=firstname;
document.getElementById('firstname').value=lastname;
document.getElementById('accountnumber').value=accountnumber;
}
}
}
</script>
In the body I have an input textfield with a button with an on click:
<td>Enter Account holder ID : </td>
<td><input type="text" id="playerid" size="10"/>
<input type="button" value="Get Details" onclick="getMessage()"/>
</tr>
<tr>
<td>Account holder Last Name : </td>
<td> <input type="text" id="lastname" size="10"/> </td>
</tr>
<tr>
<td>Account holder First Name : </td>
<td> <input type="text" id="firstname" size="10"/> </td>
</tr>
<tr>
<td>Account number : </td>
<td> <input type="text" id="accountnumber" size="10"/> </td>
</tr>
What am I missing as it is not returning anything :(
I believe your id value for the 'accountholderid' was looking for 'Id' instead of 'playerid'.
May I ask why you are calling 'eval' on the value? Do you need parseInt?
(function () {
var request = null;
function createRequest() {
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject('MsXML2.XMLHTTP');
} catch (othermicrosoft) {
try {
request = new ActiveXObject('Microsoft.XMLHTTP');
} catch (failed) {
request = null;
}
}
}
if (request === null) {
alert('Error creating request object!');
}
}
function getMessage() {
createRequest();
var accountholderid = document.getElementById('playerid').value,
id = eval(accountholderid),
url = 'http://localhost:8080/BankProjectApi/webresources/bankprojectapi.accountholder/' + id;
request.onreadystatechange = handleResponse;
request.open("GET", url, true);
request.send(null);
}
function handleResponse() {
if (request.readyState === 4 && request.status === 200) {
var xmlDocument = request.responseXML,
firstname = xmlDocument.getElementsByTagName('firstname'),
lastname = xmlDocument.getElementsByTagName('lastname'),
accountnumber = xmlDocument.getElementsByTagName('accountnumber');
for(var i = 0, max = firstname.length; i < max; i += 1) {
var firstname = firstname[i].childNodes[0].nodeValue,
lastname = lastname[i].childNodes[0].nodeValue,
accountnumber = accountnumber[i].childNodes[0].nodeValue;
document.getElementById('lastname').value = firstname;
document.getElementById('firstname').value = lastname;
document.getElementById('accountnumber').value = accountnumber;
}
}
}
}());
Also, I did a quick refactoring of your code to aid in my assessing the issue, adhere to more community conventions as well as avoid common JS pitfalls. (ex. closure, missing var declarations, ===, curlys everywhere, single variable pattern, and some others).