We are trying to implement infinite scroll in data grid in an ASP.NET Core MVC application. Searched a lot but could not find a good solution. Has any one used infinite scroll in data grid in an ASP.NET Core MVC . If so can you provide any guidance
I faced the same problem. Here is my solution. It works on nearly any table:
InfinityScroll.js
function InfinitiySroll(iTable, iAction, iParams) {
this.table = iTable; // Reference to the table where data should be added
this.action = iAction; // Name of the conrtoller action
this.params = iParams; // Additional parameters to pass to the controller
this.loading = false; // true if asynchronous loading is in process
this.AddTableLines = function (firstItem) {
this.loading = true;
this.params.firstItem = firstItem;
// $("#footer").css("display", "block"); // show loading info
$.ajax({
type: 'POST',
url: self.action,
data: self.params,
dataType: "html"
})
.done(function (result) {
if (result) {
$("#" + self.table).append(result);
self.loading = false;
}
})
.fail(function (xhr, ajaxOptions, thrownError) {
console.log("Error in AddTableLines:", thrownError);
})
.always(function () {
// $("#footer").css("display", "none"); // hide loading info
});
}
var self = this;
window.onscroll = function (ev) {
if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
//User is currently at the bottom of the page
if (!self.loading) {
var itemCount = $('#' + self.table + ' tr').length - 1;
self.AddTableLines(itemCount);
}
}
};
this.AddTableLines(0);
}
Here a from Visual Studio scaffold view - a little bit modified
TestData.cshtml
#model IEnumerable<Infinity_Scroll.Models.TestData>
#{
ViewData["Title"] = "TestData";
}
<h1>TestData</h1>
<table id="anyTable" class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Id)
</th>
<th>
#Html.DisplayNameFor(model => model.Field1)
</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
#section Scripts {
<script src="~/js/InfinitiySroll.js"></script>
<script>
var infinityScroll = new InfinitiySroll("anyTable", "/home/_TestData", { sortOrder: "ascending", searchString: "3" });
</script>
}
The generating of the table rows is moved into a PartialView:
_TestData.cshtml
#model IEnumerable<Infinity_Scroll.Models.TestData>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Id)
</td>
<td>
#Html.DisplayFor(modelItem => item.Field1)
</td>
</tr>
}
And here is the Controller part:
...
private const int BATCH_SIZE = 50;
public IActionResult TestData()
{
return View();
}
[HttpPost]
public IActionResult _TestData(string sortOrder, string searchString, int firstItem = 0)
{
List<TestData> testData = new List<TestData>();
// Generate test data
for (int i = 1; i < 500; i++)
{
testData.Add(new TestData() { Id = i, Field1 = "This is row " + i.ToString() });
}
// Sort and filter test data
IEnumerable<TestData> query;
if (sortOrder.ToLower() == "descending")
{
query = testData.OrderByDescending(m => m.Field1);
}
else
{
query = testData.OrderBy(m => m.Field1);
}
if (!String.IsNullOrEmpty(searchString)) query = query.Where(m => m.Field1.Contains(searchString));
// Extract a portion of data
var model = query.Skip(firstItem).Take(BATCH_SIZE).ToList();
if (model.Count() == 0) return StatusCode(204); // 204 := "No Content"
return PartialView(model);
}
The model:
TestData.cs
namespace Infinity_Scroll.Models
{
public class TestData
{
public int Id { get; set; }
public string Field1 { get; set; }
}
}
You can download a simple Visual Studio example here: https://github.com/ThomasBrockmann/InfinityScroll
Related
I have a form which adds bill details, like in the screenshot:
In this form person first add the entries that are stored in the session through this code:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(string nameValueInsert, string nameValueSubmit, CreateBillViewModel model, int? Patient_id)
{
int count = 0;
var button = nameValueInsert ?? nameValueSubmit;
if (button == "Insert")
{
if (Session["templist"] == null)
{
List<PatientViewModel> lst = new List<PatientViewModel>();
lst.Add(new PatientViewModel()
{ Count = count,
PatientAppointmentID = Int32.Parse(Request.Form["PatientAppointmentID"]),
// BillNo = Request.Form["BillNo"],
Amount = double.Parse(Request.Form["Amount"]),
Description = Request.Form["Description"]
});
Session["templist"] = lst;
}
else
{
List<PatientViewModel> lst = (List<PatientViewModel>)Session["templist"];
lst.Add(new PatientViewModel()
{
Count = lst.Count + 1,
PatientAppointmentID = Int32.Parse(Request.Form["PatientAppointmentID"]),
// BillNo = Request.Form["BillNo"],
Amount = double.Parse(Request.Form["Amount"]),
Description = Request.Form["Description"]
});
Session["templist"] = lst;
}
}
else
{
if (ModelState.IsValid)
{
string username = "";
HttpCookie cookie = HttpContext.Request.Cookies["AdminCookies"];
if (cookie != null)
{
username = Convert.ToString(cookie.Values["UserName"]);
}
tblPatientBill patientbill = new tblPatientBill();
patientbill.PatientAppointmentID = model.PatientAppointmentID;
// patientbill.BillNo = model.ID;
patientbill.Amount = model.AmountTotal;
patientbill.Description = model.Note;
patientbill.Discount = model.Discount;
patientbill.CreatedAt = model.CreatedAt;
patientbill.CreatedBy = username;
patientbill.is_active = true;
db.tblPatientBills.Add(patientbill);
db.SaveChanges();
int PatientBill_ID = Convert.ToInt32(patientbill.ID);
List<PatientViewModel> lst = (List<PatientViewModel>)Session["templist"];
if (lst != null)
{
tblPatientBillDetail billdetail = new tblPatientBillDetail();
foreach (var item in lst)
{
billdetail.PatientBillID = PatientBill_ID;
billdetail.Amount = item.Amount;
billdetail.CreatedAt = DateTime.UtcNow;
billdetail.CreatedBy = username;
billdetail.Description = item.Description;
billdetail.is_active = true;
db.tblPatientBillDetails.Add(billdetail);
db.SaveChanges();
}
Session.Clear();
}
return RedirectToAction("Print", new { Billid = #PatientBill_ID });
}
}
return View(model);
}
}
}
and after when done with all the entries upon submit all the record is saved into the database.
Now what I am trying to do is if while entering the entries if the user want to delete any row he should be able to delete it from session and upon finalizing the remaining data should go into the DB for which i am doing the following approach:
Id is going to controller through Ajax call:
$("body").on("click", "#tblBills .Delete", function () {
if (confirm("Do you want to delete this row?")) {
var row = $(this).closest("tr");
var Id = row.find("span").html();
console.log("Id");
$.ajax({
type: "POST",
url: "/Session_Delete",
data: '{ID: ' + Id+ '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("hello");
$("#test").remove();
}
});
}
});
and in the controller, I am removing the row from session like this:
[HttpPost]
public ActionResult DeleteBillSession(int ID)
{
List<PatientViewModel> lst = (List<PatientViewModel>)Session["templist"];
lst.Remove(lst.FirstOrDefault(t => t.Count == ID));
Session["templist"] = lst;
return Json(new { success = "Valid" }, JsonRequestBehavior.AllowGet);
}
The problem is it is removing the row from session but it is deleting the last in the sequence not the one which i have selected to be deleted.
If someone gets into the same situation the issue is resolved like this:
View:
<table id="tblBills" class="table table-bordered table-striped table-hover js-basic-example dataTable">
<tr>
<th style="width:100px">Patient Appointmnet ID</th>
<th style="width:100px">Amount</th>
<th style="width:150px">Description</th>
<th style="width:40px">Action</th>
</tr>
#{
double? AmountTotal = 0;
if (Session["templist"] != null)
{
List<PatientViewModel> lst = (List<PatientViewModel>)Session["templist"];
int count = 0;
foreach (var o in lst)
{
<tr>
<td class="Count" style="display:none">
<span>#count</span>
</td>
<td class="AppointmentID">
<span>#o.PatientAppointmentID</span>
</td>
<td class="Amount">
<span>#o.Amount</span>
</td>
<td class="Description">
<span>#o.Description</span>
</td>
<td>
<a class="Delete" href="javascript:;">Delete</a>
</td>
</tr>
AmountTotal += #o.Amount;
count++;
}}
else
{
<tr>
<td colspan="4"> No Data Found</td>
</tr>
}
}
</table>
Ajax Call:
$("body").on("click", "#tblBills .Delete", function () {
if (confirm("Do you want to delete this row?")) {
var row = $(this).closest("tr");
var id= row.find("span").html();
$.ajax({
type: "POST",
url: "/Session_Delete",
data: '{ID: ' + id+ '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$("#tblBills").load(window.location + " #tblBills");
}
});
}
});
Controller Method:
[HttpPost]
public ActionResult DeleteBillSession(int ID)
{
List<PatientViewModel> lst = (List<PatientViewModel>)Session["templist"];
lst.RemoveAt(ID);
Session["templist"] = lst;
// return new EmptyResult();
return Json(new { success = "Valid" }, JsonRequestBehavior.AllowGet);
}
I have the dropdown trigger an ajax post that sends the selected value of country dropdown .
model class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MVC_4___A_Registration_Form.Models
{
public class ModelServices
{
private readonly MyCompanyEntities entities = new MyCompanyEntities();
public IEnumerable<Country> GetCountryList()
{
return entities.Countries.ToList();
}
public IEnumerable<countryState> GetStateByCountry(int CountryID)
{
return entities.countryStates.Where(s => s.CountryId == CountryID).ToList();
}
public IList<EmployeeRegInfo> GetAllEmployeeList()
{
var myQuery = (from e in entities.Employees
join c in entities.Countries on e.Country equals c.CountryId
join s in entities.countryStates on e.State equals s.StateId
select new EmployeeRegInfo()
{
Id = e.Id,
Emp_ID = e.Emp_ID,
Dept = e.Dept,
Name = e.Name,
CountryName = c.County,
StateName = s.State,
City = e.City,
Mobile = e.Mobile
});
return myQuery.ToList();
}
public bool IsEmpAlreadyExist(string EMP_CODE)
{
bool IsRecordExist = false;
var result = (from t in entities.Employees
where t.Emp_ID == EMP_CODE
select t).SingleOrDefault();
if (result != null)
{
IsRecordExist = true;
}
return IsRecordExist;
}
public void AddNewEmployee(Employee emp)
{
entities.Employees.Add(emp);
entities.SaveChanges();
}
}
}
create.cshtml
#model MVC_4___A_Registration_Form.Models.EmployeeRegInfo
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
#ViewBag.ErrorMsg
<table>
<tr>
<td>
#Html.LabelFor(model => model.Emp_ID)
</td>
<td>#Html.EditorFor(model => model.Emp_ID)
#Html.ValidationMessageFor(model => model.Emp_ID)</td>
</tr>
<tr>
<td>
#Html.LabelFor(model => model.Name)
</td>
<td>#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)</td>
</tr>
<tr>
<td>#Html.LabelFor(model => model.Dept)
</td>
<td>#Html.EditorFor(model => model.Dept)
#Html.ValidationMessageFor(model => model.Dept)</td>
</tr>
<tr>
<td>
#Html.LabelFor(model => model.Country)</td>
<td>#Html.DropDownList("Country", ViewBag.Country as SelectList, new { Styles = "width:300px" })</td>
</tr>
<tr>
<td>#Html.LabelFor(model => model.State)
</td>
<td>
<select id="State" name="State" style="width: 200px"></select>
#Html.ValidationMessageFor(model => model.State)</td>
</tr>
<tr>
<td>#Html.LabelFor(model => model.City)</td>
<td>#Html.EditorFor(model => model.City)
#Html.ValidationMessageFor(model => model.City)
</td>
</tr>
<tr>
<td>
#Html.LabelFor(model => model.Mobile)</td>
<td>#Html.EditorFor(model => model.Mobile)
#Html.ValidationMessageFor(model => model.Mobile)
</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" value="Add Employee" /></td>
</tr>
</table>
}
<script type="text/javascript">
$(document).ready(function () {
$("#Country").change(function () {
var url = "/ManageEmployee/GetStatesByCountry";
var countryID = $("#Country").val();
$.post(url, { countryID: countryID }, function (data) {
$("#State").empty();
var items;
$.each(data, function (i, states) {
items += "<option value=" + states.StateId + ">" + states.State + "</option>";
});
$("#State").html(items);
});
});
});
</script>
controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVC_4___A_Registration_Form.Models;
namespace MVC_4___A_Registration_Form.Controllers
{
public class ManageEmployeeController : Controller
{
ModelServices model = new ModelServices();
//
// GET: /ManageEmployee/
public ActionResult Index()
{
IList<EmployeeRegInfo> empList = new List<EmployeeRegInfo>();
empList = model.GetAllEmployeeList();
return View(empList);
}
public ActionResult Create()
{
IEnumerable<Country> country;
country = model.GetCountryList();
ViewBag.Country = new SelectList(country, "CountryId", "County", "CountryId");
return View();
}
[HttpPost]
public ActionResult Create(FormCollection collection)
{
bool checkEmpCodeExist = false;
checkEmpCodeExist = model.IsEmpAlreadyExist(collection["Emp_ID"]);
if (!checkEmpCodeExist)
{
try
{
Employee emp = new Employee();
emp.Emp_ID = collection["Emp_ID"];
emp.Name = collection["Name"];
emp.Dept = collection["Dept"];
emp.Country = Convert.ToInt32(collection["Country"]);
emp.State = Convert.ToInt32(collection["State"]);
emp.City = collection["City"];
emp.Mobile = collection["Mobile"];
model.AddNewEmployee(emp);
return RedirectToAction("Index");
}
catch (Exception ex)
{
return RedirectToAction("Create");
}
}
else
{
ViewBag.ErrorMsg = "Employee Code Already Exist";
return RedirectToAction("Create");
}
}
public JsonResult GetStatesByCountry(int id)
{
var states = model.GetStateByCountry(id);
return Json(states, JsonRequestBehavior.AllowGet);
}
}
}
I want to load state dropdown on selection of country dropdown.But i am unable to do this.
Please help to load state dropdown on selection of country dropdown.
I want to load state dropdown on selection of country dropdown.But i am unable to do this.
Please help to load state dropdown on selection of country dropdown.
Hey I got the answer
some change in ajax code and controller
$(document).ready(function () {
$("#Country").change(function () {
var url = "/ManageEmployee/GetStatesByCountry";
var countryID = $("#Country").val();
$.ajax({
url: url,
data: { id: countryID },
cache: false,
type: "POST",
success: function (data) {
var markup = "<option value='0'>Select City</option>";
for (var x = 0; x < data.length; x++) {
markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
}
$("#State").html(markup).show();
},
error: function (reponse) {
alert("error : " + reponse);
}
});
});
});
[HttpPost]
public JsonResult GetStatesByCountry(string id)
{
int ids = Convert.ToInt32(id);
var states = model.GetStateByCountry(ids);
SelectList obgcity = new SelectList(states, "StateId", "State", 0);
return Json(obgcity);
}
I am attempting to implement paging and sorting into my Index view. I am following the example at http://www.codeguru.com/csharp/.net/net_asp/mvc/implementing-sorting-and-paging-in-asp.net-mvc.html however my work is neither paging or sorting. I am not sure where I went wrong.
My Index view is passed a parameter when accessed so I did modify it a little however it should not have cause it to do nothing.
My PagingInfo viewModel used for the paging and sorting is as followings.
public class PagingInfo
{
public string SortField { get; set; }
public string SortDirection { get; set; }
public int PageSize { get; set; }
public int PageCount { get; set; }
public int CurrentPageIndex { get; set; }
}
My controller has
public ActionResult Index(int id)
{
DeviceLogIndex vm = new DeviceLogIndex();
var devicelogs = db.DeviceLogs
.Include(d => d.Device)
.Include(d => d.DeviceLogType)
.Include(d => d.Device.ManufacturerModel)
.Where(d => d.DeviceID == id);
{
PagingInfo info = new PagingInfo();
info.SortField = "DeviceLog";
info.SortDirection = "ascending";
info.PageSize = 4;
info.PageCount = Convert.ToInt32(Math.Ceiling((double)(db.DeviceLogs.Count()/info.PageSize)));
// info.PageCount +=1;
info.CurrentPageIndex = 0;
var query = devicelogs.OrderBy(c => c.DeviceLogID).Take(info.PageSize);
ViewBag.PagingInfo = info;
vm.DeviceLogs = query.ToList();
Device model = db.Devices.Find(id);
model.DeviceID= id;
vm.MyDeviceID = id;
return View(vm);
}
}
[HttpPost]
public ActionResult Index(PagingInfo info, int id)
{
DeviceLogIndex vm = new DeviceLogIndex();
var devicelogs = db.DeviceLogs
.Include(d => d.Device)
.Include(d => d.DeviceLogType)
.Include(d => d.Device.ManufacturerModel)
.Where(d => d.DeviceID == id);
{
IQueryable<DeviceLog> query = null;
switch (info.SortField)
{
case "EntryDate":
query = (info.SortDirection == "ascending" ?
devicelogs.OrderBy(c => c.EntryDate) :
devicelogs.OrderByDescending(c => c.EntryDate));
break;
case "LogType":
query = (info.SortDirection == "ascending" ?
devicelogs.OrderBy(c => c.DeviceLogType) :
devicelogs.OrderByDescending(c => c.DeviceLogType));
break;
}
query = query.Skip(info.CurrentPageIndex * info.PageSize).Take(info.PageSize);
ViewBag.PagingInfo = info;
vm.MyDeviceID = id;
vm.DeviceLogs = query.ToList();
return View(vm);
}
}
And my View contains these parts
#model AQB_MON.ViewModels.DeviceLogIndex
<script>
$(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>
#{
ViewBag.Title = "Index";
}
#{
AQB_MON.ViewModels.PagingInfo info = ViewBag.PagingInfo;
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create", new { id = Model.MyDeviceID})
</p>
#using (Html.BeginForm("Index", "DeviceLog", FormMethod.Get))
{
#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)
to set the Headers that are sortable -
<th>
<a href="#" data-sortfield="LogType"
class="header">Device Log Type</a>
</th>
<th>
<a href="#" data-sortfield="EntryDate"
class="header">Entry Date</a>
</th>
for the paging -
<td>
#for (var i = 0; i < info.PageCount; i++)
{
if (i == info.CurrentPageIndex)
{
<span>#(i + 1)</span>
}
else
{
<a href="#" data-pageindex="#i"
class="pager">#(i + 1)</a>
}
}
</td>
It's a lot of code that does not seem to do anything. Just confused.
Here is the code for controllers and view. I want to display the both views on the same webpage in ASP.NET MVC. How to achieve this goal?
Controller:
public ActionResult LetterList()
{
LetterPage.Models.ModelView obj = new LetterPage.Models.ModelView();
obj.letterDetail = new List<LetterList>()
{
new LetterList() { ListId = "1", ListName = "A" },
new LetterList() { ListId = "2", ListName= "B" },
new LetterList() { ListId = "3", ListName= "C" },
new LetterList() { ListId ="4", ListName= "D"}
};
return View(obj);
}
public ActionResult Showimage(string ListId)
{
Post post = new Post();
var letterList = post.FindByletter_Id(ListId);
return View(letterList);
}
View Of LetterList
#model LetterPage.Models.ModelView
<div>
#{
foreach (var item in Model.letterDetail)
{
<div>
#item.ListName
</div>
}
}
</div>
ShowImage view:
#model IList< LetterPage.Models.hurf_e_tahaji>
#{
ViewBag.Title = "ShowImage";
}
<table class="table">
<tr>
<th>
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
<img src="#Url.Content("item.Letter_Pic") "/>
</td>
</tr>
}
</table>
When I created these views as partial views and render them into another view exception occurs on the Foreach loop at model.
You can use PartialView:
[HttpPost]
public PartialViewResult LetterList()
{
if (Request.IsAjaxRequest())
{
LetterPage.Models.ModelView obj = new LetterPage.Models.ModelView();
obj.letterDetail = new List<LetterList>()
{
new LetterList() { ListId = "1", ListName = "A" },
new LetterList() { ListId = "2", ListName= "B" },
new LetterList() { ListId = "3", ListName= "C" },
new LetterList() { ListId ="4", ListName= "D"}
};
return PartialView(obj);
}
return null;
}
[HttpPost]
public PartialViewResult Showimage(string ListId)
{
if (Request.IsAjaxRequest())
{
Post post = new Post();
var letterList = post.FindByletter_Id(ListId);
return PartialView(letterList);
}
return null;
}
Then you have to define your partial views (like code you posted), And inside the main view:
<div class="LetterList">
<img src="#Url.Content("~/Content/Images/arrow-spinner-blue.gif")" alt="loading" />
</div>
<div class="Showimage">
<img src="#Url.Content("~/Content/Images/arrow-spinner-blue.gif")" alt="loading" />
</div>
#section Scripts
{
<script type="text/javascript">
$(function () {
$.post('/Home/LetterList', function(data) {
$('.LetterList').html(data);
});
$.post('/Home/Showimage/' + ListId, function(data) {
$('.Showimage').html(data);
});
});
</script>
}
What can be causing the following script to only fire randomly when it feels like it? i.e. if I comment in the alert(44); it pops up sometimes once at the start when I click on page 2. Then I click other pages in the pager and no alert(44) but I get the WHOLE page reloading and not just the partial
So in effect its like I have no problem but only if I can force the Javascript Click below to run all the time when the Pager bar is clicked
$(function () {
$('#myPager').on('click', 'a', function () {
//alert(44);
$.ajax({
url: this.href,
type: 'GET',
cache: false,
success: function (result) {
$('#ResultsList').html(result);
}
});
return false;
});
});
The Javascript above is inside "$(document).ready(function () {" and part of my main file called index.cshtml
Also in index.cshtml I have
<div id="ResultsList" style="clear:both;">
#Html.Partial("IndexSearchResults")
</div>
In IndexSearchResults I have :
#model PagedList.IPagedList<AscendancyCF.Domain.Premise>
<p>
Results <span class="badge">#string.Format("{0:n0}", ViewBag.ResultCount)</span> of <span class="badge">#string.Format("{0:n0}", ViewData["TotalRecords"])</span> Premises <div id="LoadingGif"></div>
</p>
<table class="table" id="myTable" data-link="row">
<thead>
<tr>
<th>
Core Spid
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.CoreSPID)
</td>
</tr>
}
</tbody>
</table>
<div id="myPager">
#Html.Partial("Pager")
</div>
Finally Controller Code is :
public ActionResult Index()
{
if (!Request.IsAuthenticated)
return View("~/Views/Shared/NotAuthorised.cshtml");
ViewData["TotalRecords"] = _db.FindAllPremises().Count();
ViewData["ResultCount"] = 0;
ViewBag.InitialPageCount = 10;
var obj = _db.FindAllPremiseEmpty();
return View("Index", obj.ToPagedList(1, 10));
}
public ActionResult IndexSearch(int? page, string searchSPID, string searchPremise, string searchPostcode, int optVacant, int OptOurSpids, string searchCompany, string searchLP)
{
var searchResults = getSearchResults(searchSPID, searchPremise, searchPostcode, optVacant, OptOurSpids, searchCompany, searchLP);
ViewData["TotalRecords"] = _db.FindAllPremises().Count();
ViewBag.ResultCount = searchResults.Count();
ViewBag.searchSPID = searchSPID;
ViewBag.searchPremise = searchPremise;
ViewBag.searchPostcode = searchPostcode;
ViewBag.optVacant = optVacant;
ViewBag.OptOurSpids = OptOurSpids;
ViewBag.searchCompany = searchCompany;
ViewBag.searchLP = searchLP;
int pageSize = 5;
int pageNumber = (page ?? 1);
if (searchResults == null)
return View("NotFound");
if (Request.IsAjaxRequest())
{
return PartialView("IndexSearchResults", searchResults.ToPagedList(pageNumber, pageSize));
}
return View("Index", searchResults.ToPagedList(pageNumber, pageSize));
}
I have code that gets fired from SEARCH button in index.aspx. This now only runs once and fails after I have clicked on the pager, here it is:
function performSearch() {
var url = '/Premise/IndexSearch';
var data = {
searchSPID: $('#SearchSPID').val().toString(),
searchPremise: $('#SearchPremise').val().toString(),
searchPostcode: $('#SearchPostcode').val().toString(),
optVacant: $("input[name='OptVacantOrOccupied']:checked").attr("id"),
OptOurSpids: $("input[name='OptOurSpids']:checked").attr("id"),
SearchCompany: $('#SearchCompany').val().toString(),
SearchLP: $('#SearchLP').val().toString()
};
$("#ResultsList").load(url, data, function () {
$('#LoadingGif').empty();
});
$('#LoadingGif').empty().html('<img src="/Content/images/ajax-loader.gif" width=31 height=31 alt="Loading image" />');
}
Your #myPager event handler is lost when the page is updated due to the element being removed from the dom. If you want to do this kind of thing, always attach your dom event to a part of the page that doesn't get removed, your handlers won't get destroyed then.
Try and keep to as close to your original element as possible to stop a mass of handlers slowing down your page.
Here is an updated script:
$(function () {
$('#ResultsList').on('click', '#myPager a', function (evt) {
var target = $(evt.currentTarget);
$.ajax({
url: target.attr("href"),
type: 'GET',
cache: false,
success: function (result) {
$('#ResultsList').html(result);
}
});
return false;
});
});
I haven't tested this, but it looks right.