MVC4 WebGrid in dialog hangs in IE and no pagination in Chrome - asp.net-mvc-4

MVC4: I am new to using WebGrid with MVC. Code below produces WebGrid inside dialog, but pagination does not work in Chrome ( blank page displayed) and in IE : dialog with WebGrid shown , but IE hangs (seem to be doing something and then hangs, no chance to try pagination even).
What is wrong with my code?
Thank you
HomeController.cs
public ActionResult MyReport (int id) // get here on click in SelectList
{
List<MyLocation> myl = MyLocation.GetAllLocations(31); // static method in MyLocation model
return View(myl);
}
public ActionResult MyLocationDetails (int id)
{
LocationDetails ld = new LocationDetails();
List<LocationDetails> model = ld.GetTestLocationDetails(); //model has 20 records
return PartialView(model); // MyLocationDetails partial view to be displayed in Dialog
}
MyReport.cshtml View that should display dialog
#model IEnumerable<MyLocation>
#Html.ActionLink("Location Details", "MyLocationDetails", null, new { id = 234 }, new { #class = "LocDetails" })
<div id="LocDetails-dialog"></div>
<script type="text/javascript">
$(function () {
$('#LocDetails-dialog ').dialog({
autoOpen: false,
width: 400,
resizable: false,
modal: true
});
$('.LocDetails').click(function() {
$('#LocDetails-dialog ').load(this.href, function() {
$(this).dialog('open');
});
return false;
});
});
</script>
MyLocationDetails.cshtml
#model List
<div>
#if (Model != null)
{
if (Model.Count != 0)
{
<div id="divLocDetails">
#{WebGrid grid = new WebGrid(source: Model,
rowsPerPage: 5,
canPage: true
);
grid.SortDirection = SortDirection.Ascending;
}
#grid.GetHtml(
htmlAttributes: new { id = "LocDetails" },
mode: WebGridPagerModes.All,
firstText: "First",
previousText: "Prev",
nextText: "Next",
lastText: "Last",
columns: new[] {
grid.Column("city", header: "City", canSort: true),
grid.Column("country", header: "Country", canSort: false)
}
)
</div>
}
else
{
<label>No results</label>
}
}
</div>

Related

How to build multiple drill down using highchart correctly?

I want to make multiple drill down chart using framework Yii2. I want to make student's chart based by age. I have installed highcharts via composer. I also have registered it to my php file, but I don't know why the drilldown chart doesn't work. I think, it's because my incorrect codes.
Here is my tables:
facultyin2011
department2011
major2011
Here is my controller:
<?php
namespace app\controllers;
use yii\web\Controller;
use yii\helpers\Json;
class MagisterrinciController extends Controller
{
public function actionIndex()
{
//data usia fakultas
$faculty = (new \yii\db\Query())
->select(['Faculty'])
->from('facultyin2011')
->limit(10)
->column();
$age1 = (new \yii\db\Query())
->select(['lessthan25'])
->from('facultyin2011')
->limit(10)
->column();
$age2 = (new \yii\db\Query())
->select(['btween25to29'])
->from('facultyin2011')
->limit(10)
->column();
$age1 = array_map('floatval', $age1);
$age2 = array_map('floatval', $age2);
$data['ageforfacultystudent'] = json_encode($faculty);
$data['age1'] = json_encode($age1);
$data['age2'] = json_encode($age2);
// next
$department = (new \yii\db\Query())
->select(['Department'])
->from('department2011')
->limit(10)
->column();
$agedepartment1 = (new \yii\db\Query())
->select(['lessthan25'])
->from('department2011')
->limit(10)
->column();
$agedepartment2 = (new \yii\db\Query())
->select(['btween25to29'])
->from('department2011')
->limit(10)
->column();
$agedepartment1 = array_map('floatval', $agedepartment1);
$agedepartment2 = array_map('floatval', $agedepartment2);
$data['agefordepartmentstudent'] = json_encode($department);
$data['agedepartment1'] = json_encode($agedepartment1);
$data['agedepartment2'] = json_encode($agedepartment2);
//next
$majorstudent = (new \yii\db\Query())
->select(['major'])
->from('major2011')
->limit(10)
->column();
$agemajor1 = (new \yii\db\Query())
->select(['lessthan25'])
->from('department2011')
->limit(10)
->column();
$agemajor2 = (new \yii\db\Query())
->select(['btween25to29'])
->from('department2011')
->limit(10)
->column();
$agemajor1 = array_map('floatval', $agemajor1);
$agemajor2 = array_map('floatval', $agemajor2);
$data['ageformajorstudent'] = json_encode($majorstudent);
$data['agemajor1'] = json_encode($agemajor1);
$data['agemajor2'] = json_encode($agemajor2);
return $this->render('index',$data);
}
}
Here is my index view:
<?php
use app\assets\HighchartsAsset;
HighchartsAsset::register($this);
$this->title = 'Highcharts Test';
?>
<!-- data selanjutnya -->
<div class="container">
<div class="row">
<div class="col-md-6 col-sm-6 col-xs-12">
<div class="x_panel">
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
<?php $this->registerJs("
$(function () {
// Create the chart
$('#container').highcharts({
chart: {
type: 'column'
},
title: {
text: 'Basic drilldown'
},
xAxis: {
categories: $ageforfacultystudent
},
legend: {
enabled: false
},
plotOptions: {
series: {
borderWidth: 0,
dataLabels: {
enabled: true,
}
}
},
series: [
{
name: 'lessthan25',
data: $age1,
drilldown: 'department1'
},
{
name: 'btween25to29',
data: $age2,
drilldown: 'department2'
}],
drilldown: {
series: [{
id: 'department1',
name: 'Departemen',
data: [{
name: 'lessthan25',
data: $agedepartment1,
drilldown: 'major1'
},
{
name: 'btween25to29',
data: $agedepartment2,
drilldown: 'major2'
}
]
}, {
id: 'major1',
data: $agemajor1
},
{
id: 'major2',
data: $agemajor2
}]
}
})
});
")?>
</div>
</div>
here is the result:
those charts can't be drilled down.
When I checked the console, there is no error message.
Could anybody please correct my codes above? It's gonna help me a lot. Thank you in advance

keep selected item of dropdownlist as you move from page to page in a webgrid

I have a page that has a dropdownlist and a webgrid. The webgrid has pagenumbers. If I am on page 1 and I select page 2 the item
selected on the dropdown is lost and goes back to "Select Branch"
I want to be able to keep the item selected as I move from page to page. How do I do that? I tried the request.form but did not work
public ActionResult Index()
{
var currentUser = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();
Edmviewmodel objedmtest = new Edmviewmodel();
string ddlState_SelectedStateValue = Request.Form["ddlDropDownList"];
if (currentUser != null)
{
try
{
objedmtest = _edmDataService.GetRequiredData("A05");
ViewData["SelectList"] = HttpContext.Session["SelectList"] ?? new List<string>();
}
catch (Exception ex)
{
//logger.Error(ex);
}
}
return View(objedmtest);
}
Here is the html code.
#{
var grid = new WebGrid(source: Model.GetCatDataByLocation,
defaultSort: "CustomerName",
canSort: true,
rowsPerPage: 5
);
}
<div>
<div>
<label for="ddlBranch">Branch:</label>
#Html.DropDownList("ddlDropDownList", Model.BranchesSelectList, "Select Branch", new { #class = "css-class" })
</div>
<div>
#grid.GetHtml(
tableStyle: "grid",
headerStyle: "head",
alternatingRowStyle: "alt",
columns: grid.Columns(
grid.Column("Select", format: #<text><input name="CustomerName" type="checkbox" value="#item.CustomerName" #Html.Raw(((List<string>)ViewData["SelectList"]).Contains(#item.CustomerName) ? "checked" : "") /></text>),
grid.Column("CustomerName", "CustomerName"),
grid.Column("CustomerNumber", "CustomerNumber"),
grid.Column("Orderdate", "Orderdate", canSort: false),
grid.Column("OrderNumber", "OrderNumber"),
grid.Column("Routenumber", "Routenumber"),
grid.Column("Primaryrep", "Primaryrep"),
grid.Column("Isvalidated", "Isvalidated")
)
)
</div>
<div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
//check for existance of query string
var urlg = window.location.href; //global url
var previousIndex = 0;
if (urlg.indexOf("ap") > 0) {
previousIndex = (urlg.substring(urlg.indexOf("ap=") + 3));
}
$('select>option:eq(' + previousIndex + ')').prop('selected', true); //zero-based
$("a").click(function (event) {
$("td a").each(function () {
var old = $(this).attr('href');
idx = $("select[name='ddlDropDownList'] option:selected").index();
$(this).attr("href", old + "&ap=" + idx);
});
});
});
</script>

Jquery dataTable plugin, Can I combine initialization (delete chekbox rows, and export to csv)?

I have successfully implemted the plugin, now I need functionality. There are no examples of mixed implementation, ie. delete all with selected checkbox, with csv/print. Just examples of single function implementation. Which is ok but I think there will be an application or 2 that need 2 to 3 of the plugin extentions to be a complete application.
my code, mvc 4 razor view:
#{
ViewBag.Title = "Price Comparison";
}
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title> Learning JQuery</title>
<!---CSS-->
<link href="~/Content/Site.css" rel="stylesheet" />
<!---JQuery-->
<link href="~/Content/DataTables/css/dataTables.tableTools.css" rel="stylesheet" />
<link href="~/Content/DataTables/css/dataTables.tableTools.min.css" rel="stylesheet" />
<script src="~/Scripts/DataTables/dataTables.tableTools.js"></script>
<script src="~/Scripts/DataTables/dataTables.tableTools.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
url: 'PricingService.asmx/GetPricing',
method: 'post',
dataType: 'json',
success: function (data) {
var table = $('#example').dataTable({
select: true,
data: data,
columns: [
{ 'data': 'Manufacturer' },
{ 'data': 'Product' },
{ 'data': 'SKU' },
{
'data': 'BarcodePrice',
'render': function (barcodeprice) {
return "$" + barcodeprice;
}
},
{
'data': 'ScansourcePrice',
'render': function (scansourceprice) {
return "$" + scansourceprice;
}
},
{
'data': 'BluestarPrice',
'render': function (bluestarprice) {
return "$" + bluestarprice;
}
},
]
});
var tableTools = new $.fn.dataTable.TableTools(table, {
'sSwfPath': '//cdn.datatables.net/tabletools/2.2.0/swf/copy_csv_xls.swf',
'aButtons': [{
'sExtends': 'copy',
'bShowAll': false
},
{
'sExtends': 'print',
'bShowAll': false
},
{
'sExtends': 'csv',
'bShowAll': false
},
{
'sExtends': 'xls',
'bShowAll': false
},
]
});
$(tableTools.fnContainer()).insertBefore('#example_wrapper')
}
});
});
</script>
</head>
<body>
<form id="frm-example" action="/nosuchpage" method="POST">
<div style="border:1px solid black; padding:3px; width:1200px">
<table id="example">
<thead>
<tr>
<th>Manufacturer</th>
<th>Product</th>
<th>SKU</th>
<th>Our Price</th>
<th>Scansource Price</th>
<th>Bluestar Price</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Manufacturer</th>
<th>Product</th>
<th>SKU</th>
<th>Our Price</th>
<th>Scansource Price</th>
<th>Bluestar Price</th>
</tr>
</tfoot>
</table>
<hr>
<p>Press <b>Submit</b> and check console for URL-encoded form data that would be submitted.</p>
<p><button>Submit</button></p>
<b>Data submitted to the server:</b><br>
<pre id="example-console">
</pre>
</div>
</form>
</body>
</html>
1.I can not initialize ('#example') more than once, so how in the world can I combine the following into the ajax code in my view?
//
// Updates "Select all" control in a data table
//
function updateDataTableSelectAllCtrl(table){
var $table = table.table().node();
var $chkbox_all = $('tbody input[type="checkbox"]', $table);
var $chkbox_checked = $('tbody input[type="checkbox"]:checked', $table);
var chkbox_select_all = $('thead input[name="select_all"]', $table).get(0);
// If none of the checkboxes are checked
if($chkbox_checked.length === 0){
chkbox_select_all.checked = false;
if('indeterminate' in chkbox_select_all){
chkbox_select_all.indeterminate = false;
}
// If all of the checkboxes are checked
} else if ($chkbox_checked.length === $chkbox_all.length){
chkbox_select_all.checked = true;
if('indeterminate' in chkbox_select_all){
chkbox_select_all.indeterminate = false;
}
// If some of the checkboxes are checked
} else {
chkbox_select_all.checked = true;
if('indeterminate' in chkbox_select_all){
chkbox_select_all.indeterminate = true;
}
}
}
$(document).ready(function (){
// Array holding selected row IDs
var rows_selected = [];
var table = $('#example').DataTable({
'ajax': {
'url': 'ids-arrays.txt'
},
'columnDefs': [{
'targets': 0,
'searchable':false,
'orderable':false,
'className': 'dt-body-center',
'render': function (data, type, full, meta){
return '<input type="checkbox">';
}
}],
'order': [1, 'asc'],
'rowCallback': function(row, data, dataIndex){
// Get row ID
var rowId = data[0];
// If row ID is in the list of selected row IDs
if($.inArray(rowId, rows_selected) !== -1){
$(row).find('input[type="checkbox"]').prop('checked', true);
$(row).addClass('selected');
}
}
});
// Handle click on checkbox
$('#example tbody').on('click', 'input[type="checkbox"]', function(e){
var $row = $(this).closest('tr');
// Get row data
var data = table.row($row).data();
// Get row ID
var rowId = data[0];
// Determine whether row ID is in the list of selected row IDs
var index = $.inArray(rowId, rows_selected);
// If checkbox is checked and row ID is not in list of selected row IDs
if(this.checked && index === -1){
rows_selected.push(rowId);
// Otherwise, if checkbox is not checked and row ID is in list of selected row IDs
} else if (!this.checked && index !== -1){
rows_selected.splice(index, 1);
}
if(this.checked){
$row.addClass('selected');
} else {
$row.removeClass('selected');
}
// Update state of "Select all" control
updateDataTableSelectAllCtrl(table);
// Prevent click event from propagating to parent
e.stopPropagation();
});
// Handle click on table cells with checkboxes
$('#example').on('click', 'tbody td, thead th:first-child', function(e){
$(this).parent().find('input[type="checkbox"]').trigger('click');
});
// Handle click on "Select all" control
$('#example thead input[name="select_all"]').on('click', function(e){
if(this.checked){
$('#example tbody input[type="checkbox"]:not(:checked)').trigger('click');
} else {
$('#example tbody input[type="checkbox"]:checked').trigger('click');
}
// Prevent click event from propagating to parent
e.stopPropagation();
});
// Handle table draw event
table.on('draw', function(){
// Update state of "Select all" control
updateDataTableSelectAllCtrl(table);
});
// Handle form submission event
$('#frm-example').on('submit', function(e){
var form = this;
// Iterate over all selected checkboxes
$.each(rows_selected, function(index, rowId){
// Create a hidden element
$(form).append(
$('<input>')
.attr('type', 'hidden')
.attr('name', 'id[]')
.val(rowId)
);
});
// FOR DEMONSTRATION ONLY
// Output form data to a console
$('#example-console').text($(form).serialize());
console.log("Form submission", $(form).serialize());
// Remove added elements
$('input[name="id\[\]"]', form).remove();
// Prevent actual form submission
e.preventDefault();
});
});
2.This successfully added the csv and other buttons along with the search and pagination. But the csv and copy still selects all the pages in the table instead of the one displayed.I followed the documentation and used the sExtends, but it still does not work.
Any help Please?

knockout.js binding issue when trying to refresh data

I am using knockout.js data binding. At the page load the binding works fine and data is shown on the page correctly. Then I try to push data back to the database and the push is successful. The database receives the data OK.
The problem comes when I try to reload the data upon push success. At this time the binding already happen once (at the page load). If I don't bind it again the data on the page does not refresh. If I do the binding again knockout.js issues an error "cannot bind multiple times". If I do a cleanup before rebinding I receive an error "nodeType undefined".
Can anyone tell me what I have missed here? I am using ASP.NET MVC 4.0 with knockout.js 3.0.0.
Controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplJSON.Controllers
{
public class KnockoutController : Controller
{
//
// GET: /Knockout/
public ActionResult Index()
{
return View();
}
[HttpGet]
public JsonResult GetProductList()
{
var model = new List<Product>();
try
{
using (var db = new KOEntities())
{
var product = from p in db.Products orderby p.Name select p;
model = product.ToList();
}
}
catch (Exception ex)
{ throw ex; }
return Json(model, JsonRequestBehavior.AllowGet);
}
// your controller action should return a JsonResult. There's no such thing as a controller action that returns void. You have specified dataType: 'json' so return JSON. That's it. As far as what parameter this controller action should take, well, from the JSON you are sending ({"Name":"AA"}) it should be a class that has a Name property of type string.
// modify your action signature to look like this: [HttpPost] public ActionResult SaveProduct (Product product) { ... return Json(new { success = true }); }. Or get rid of this dataType: 'json' attribute from your AJAX request if you don't want to return JSON. In this case you could return simply status code 201 (Created with empty response body): return new HttpStatusCodeResult(201);.
[HttpPost]
public ActionResult SaveProduct(Product product)
{
using (var db = new KOEntities())
{
db.Products.Add(new Product { Name = product.Name, DateCreated = DateTime.Now });
db.SaveChanges();
}
return Json(new { success = true });
}
}
}
View:
#{
ViewBag.Title = "Knockout";
}
<h2>Knockout</h2>
<h3>Load JSON Data</h3>
<div id="loadJson-custom" class="left message-info">
<h4>Products</h4>
<div id="accordion" data-bind='template: { name: "product-template", foreach: product }'>
</div>
</div>
<h3>Post JSON Data</h3>
<div id="postJjson-custom" class="left message-info">
<h4>Add Product</h4>
<input id="productName" /><br />
<button id="addProduct">Add</button>
</div>
#section Scripts {
#Scripts.Render("~/bundles/knockout")
#Scripts.Render("~/bundles/livequery")
<script src="/Scripts/jquery.livequery.min.js"></script>
<style>
#accordion { width: 400px; }
</style>
<script id="product-template" type="text/html">
<h3><a data-bind="attr: {href:'#', title: Name, class: 'product'}"><span data-bind="text: Name"></span></a></h3>
<div>
<p>Here's some into about <span data-bind="text: Name" style="font-weight: bold;"></span> </p>
</div>
</script>
<script>
var isBound;
function loadJsonData() {
$.ajax({
url: "/knockout/GetProductList",
type: "GET",
contentType: "application/json",
dataType: "json",
data: {},
async: true,
success: function (data) {
var loadJsonViewModel = {
product: ko.observableArray(),
init: function () {
loadAccordion();
}
};
var a = $('loadJson-custom');
loadJsonViewModel.product = ko.mapping.fromJS(data);
if (isBound) { }
else
{
ko.applyBindings(loadJsonViewModel, $('loadJson-custom')[0]);
isBound = true;
}
loadJsonViewModel.init();
}
});
}
// push data back to the database
function pushJsonData(productName) {
var jData = '{"Name": "' + productName + '"}';
$.ajax({
url: "/knockout/SaveProduct",
type: "POST",
contentType: "application/json",
dataType: "json",
data: jData,
async: true,
success: function (data, textStatus, jqXHR) {
console.log(textStatus + " in pushJsonData: " + data + " " + jqXHR);
//ko.cleanNode($('loadJson-custom')[0]);
loadJsonData();
},
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus + " in pushJsonData: " + errorThrown + " " + jqXHR);
}
});
}
function loadAccordion() {
$("#accordion > div").livequery(function () {
if (typeof $("#accordion").data("ui-accordion") == "undefined")
{
$("#accordion").accordion({ event: "mouseover" });
}
else
{
$("#accordion").accordion("destroy").accordion({ event: "mouseover" });
}
});
}
$(function () {
isBound = false;
loadJsonData();
$("#addProduct").click(function () {
pushJsonData($("#productName").val());
});
});
</script>
}
Here is a complete solution for your question.
I have just implemented and checked.
Please have a look.
I have created a class for getting some records ie: Records.cs.
public static class Records
{
public static IList<Student> Stud(int size)
{
IList<Student> stud = new List<Student>();
for (int i = 0; i < size; i++)
{
Student stu = new Student()
{
Name = "Name " + i,
Age = 20 + i
};
stud.Add(stu);
}
return stud;
}
}
public class Student
{
public string Name { get; set; }
public int Age { get; set; }
}
Here is a controller for the respective view.
//
// GET: /HelpStack/
private static IList<Student> stud = Records.Stud(10);
public ActionResult HelpStactIndex()
{
return View();
}
[HttpGet]
public JsonResult GetRecord()
{
return Json(stud, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public void PostData(Student model)
{
//do the required code here as All data is in "model"
}
Here is a view as HTML, I have taken two section one for list and other to Add records
<div id="loadJson-custom">
<h4>Student</h4>
<table width="100%">
<tr>
<td style="width: 50%">
<div id="accordion" data-bind='template: { name: "product-template", foreach: Student }'>
</div>
</td>
<td valign="top">
<div id="NewStudent">
<input type="text" data-bind="value: Name" /><br />
<input type="number" data-bind="value: Age" /><br />
<input type="submit" data-bind="click: Save" value="AddNew" />
</div>
</td>
</tr>
</table>
Here is your scripts for Knockoutjs.
<script id="product-template" type="text/html">
<h3><a data-bind="attr: { href: '#', title: Name, class: 'product' }"><span data-bind=" text: Name"></span></a>
<br />
Age: <span data-bind="text: Age"></span>
</h3>
<div>
<p>Here's some into about <span data-bind="text: Name" style="font-weight: bold;"></span></p>
</div>
</script>
<script type="text/javascript">
//Model for insert new record
var Model = {
Name: ko.observable(''),
Age: ko.observable(''),
};
var Student = ko.observableArray([]); // List of Students
function loadData() { //Get records
$.getJSON("/HelpStack/GetRecord", function (data) {
$.each(data, function (index, item) {
Student.push(item);
});
}, null);
}
function Save() { //Save records
$.post("/HelpStack/PostData", Model, function () { //Oncomplete i have just pushed the new record.
// Here you can also recall the LoadData() to reload all the records
//Student.push(Model);
Student.unshift(Model); // unshift , add new item at top
});
}
$(function () {
loadData();
ko.applyBindings(Model, $('#NewStudent')[0]);
});
</script>
You are declaring your model inside loadJsonData function success callback, & creating new object on every success callback, move the model outside that function, create an object & use it inside loadJsonData function, it will fix the issue.

Retaining search filter with WebGrid paging MVC 4

I am unable to retain the filter (search) across pages in Webgrid. As in when next page is clicked, the search criteria is lost. Any ideas??
Partial View:
#model IEnumerable<NorthwindMVC_2.Models.GetOrdersResult>
#using NorthwindMVC_2.Models;
<input type="hidden" id="page" />
#{
ViewBag.Title = "_Grid";
Layout = null;
}
#using (Html.BeginForm(FormMethod.Get))
{
<input type="search" name="SearchString" style="width:650px; margin-right:10px" placeholder="ID, Ship Name, Ship Address, Required Date, Postal Code" id="txtSearch" />
<input type="submit" value="Search"/>
<input type="button" value="Clear" id="btnClear"/>
<script>
$("#btnClear").live("click", refreshGrid);
function refreshGrid() {
var pageNumber = '#ViewBag.page';
//$("#txtSearch").val("");
$.ajax(
{
type: "GET",
url: '#Url.Action("OrdersList", "Orders")',
data: {
searchText: $("#txtSearch").val(),
page: pageNumber
},
dataType: "html",
success: function (data) {
$("#agrid").html(data);
}
})
}
</script>
<script type="text/javascript">
var PageNumber = '#ViewBag.page';
$(document).ready(function page() {
//alert(PageNumber);
});
//var page = '#ViewBag.page';
</script>
<style type="text/css">
.webGrid { margin: 4px; border-collapse: collapse; width: auto; }
.header { background-color: #d3dce0; font-weight: bold; color: whitesmoke; }
.webGrid th, .webGrid td {border: 1px solid #C0C0C0; padding: 5px; }
.alt { background-color: lightgrey; color: #000; }
.footer { padding:10px; background-color:#d3dce0; color:black;}
.birthdate { width:200px;}
.id { width:50px;}
.general { width: 120px;}
</style>
var grid = new WebGrid(null,
defaultSort: "",
rowsPerPage: 10,
canPage:true,
ajaxUpdateContainerId:"grid",
selectionFieldName: "SearchString",
sortFieldName:"SortColumn",
sortDirectionFieldName:"SortOrder");
<div style="display:none">
#grid.Bind(Model, autoSortAndPage: false, rowCount: ViewBag.tr);
</div>
if (Model.Count() > 0)
{
<div id="grid">
#grid.GetHtml(
tableStyle: "webGrid",
headerStyle: "header",
alternatingRowStyle: "alt",
footerStyle: "footer",
mode: WebGridPagerModes.All,
numericLinksCount: 9,
firstText: "First",
lastText: "Last",
previousText: "<",
nextText: ">",
columns: grid.Columns(
grid.Column("OrderID", header:"ID", style:"id"),
grid.Column("ShipName", "Name", style:"birthdate" , format: #<text>#Html.ActionLink((string)item.ShipName, "Edit", "Orders", new { RowID = item.RowID, orderId = item.OrderID, page= (int) #ViewBag.page }, null)</text>),
grid.Column("ShipAddress", header:"Address", style:"birthdate"),
grid.Column("RequiredDate", header:"Required Date", style:"birthdate"),
grid.Column("ShipPostalCode", header:"Postal Code", style:"general"),
#*grid.Column("Action", format: #<text>
<button class="edit-user display-mode" >Edit</button>
<button class="save-user edit-mode" >Save</button>
<button class="cancel-user edit-mode" >Cancel</button>
</text>, style: "" , canSort: false)*#
//grid.Column("Edit", format: (item) => Html.ActionLink("Edit", "Edit", "Orders", new { RowID = item.RowID, orderId = item.OrderID, page= (int) #ViewBag.page }, new { style = "color:#000" })),
grid.Column("Delete", format: (item) => Html.ActionLink("Delete", "Delete", new { orderId = (int)item.OrderID }, new { onclick = "return confirm('Do you want to Delete this Order?')", style = "color:#000" })
)
)
)
</div>
}
else
{
<p>
No records found.</p>
}}
<script type="text/javascript">
var searchText = $("#txtSearch").val();
$(function () {
$('tfoot a').click(function () {
var pageNumber = '#ViewBag.page';
// $("#txtSearch").val("");
$.ajax(
{ searchText : $("#txtSearch").val(),
type: "GET",
url: '#Url.Action("OrdersList", "Orders")',
data: {
searchText: $("#txtSearch").val(),
page: pageNumber
},
dataType: "html",
success: function (data) {
$("#agrid").html(data);
}
})
// // when the user clicks on any of the pager links
// // try to extract the page number from the link and
// // set the value of the hidden field
// var SearchString = $("#txtSearch")
// var page = this.href.match(/page=([0-9])+/)[1];
// $('#page').val(page);
// alert(page);
// // submit the form so that the POST action is invoked
// // passing along the search criteria (Name and Year) along
// // with the page hidden field value to the Index action
// $('form').submit();
// // cancel the default action of the link which is to simply redirect
// // to the Index action using a GET verb.
// return false;
});
});
</script>
in your $('tfoot a').click(function ()... it will send a "GET" request ( /?page=1 ) to action method with your ajax request. You have to handle your pager link click event in this code.
you can do something like this
$('tfoot a').click(function () {
var form = $('#yourformid');
form.attr("action", this.href);
$(this).attr("href", "#");
form.submit();
});
Then only it will retain your search criteria model
please have look in to this approach