jqgrid not displaying, mvc 3 - asp.net

I am using asp.net MVC 3 , and my table is not displayed.
Then I had built another project, but in MVC 4. Everything worked fine.
My Controller code:
public JsonResult GetTodoLists(string sidx, string sord, int page, int rows, Billboard billboard) //Gets the todo Lists.
{
int pageIndex = Convert.ToInt32(page) - 1;
int pageSize = rows;
var todoListsResults = db.billboard.Select(
a => new
{
a.BillboardID,
a.Event_date,
a.Event_name,
});
int totalRecords = todoListsResults.Count();
var totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);
if (sord.ToUpper() == "DESC")
{
todoListsResults = todoListsResults.OrderByDescending(s => s.Event_name);
todoListsResults = todoListsResults.Skip(pageIndex * pageSize).Take(pageSize);
}
else
{
todoListsResults = todoListsResults.OrderBy(s => s.Event_name);
todoListsResults = todoListsResults.Skip(pageIndex * pageSize).Take(pageSize);
}
var jsonData = new
{
total = totalPages,
page,
records = totalRecords,
rows = todoListsResults
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
My View code:
<h2>Todo List</h2>
<div>
<table id="grid"></table>
<div id="pager"></div>
</div>
<head>
<title>jqGrid</title>
<link href="~/Content/jquery.jqGrid/ui.jqgrid.css" rel="stylesheet" />
<link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />
<script src="~/Scripts/jquery-1.9.1.min.js"></script>
<script src="~/Scripts/jquery-ui-1.10.4.min.js"></script>
<script src="~/Scripts/i18n/grid.locale-ru.js"></script>
<script src="~/Scripts/jquery.jqGrid.min.js"></script>
<script src="~/Scripts/Billboard.js"></script>
</head>
And my js code:
jQuery(document).ready(function () {
$("#grid").jqGrid({
url: "/Home/GetTodoLists",
datatype: 'json',
mtype: 'Get',
colNames: ['BillboardID', 'Event_date', 'Event_name', ],
colModel: [
{ key: true, hidden: true, name: 'BillboardID', index: 'BillboardID', editable: true },
{ key: false, name: 'Event_date', index: 'Event_date', width: 80, editable: true, },
{ key: false, name: 'Event_name', index: 'Event_name', editable: true, editrules: true },
],
pager: jQuery('#pager'),
rowNum: 5,
rowList: [5, 10, 15],
height: '20%',
viewrecords: true,
caption: 'Афиша',
emptyrecords: 'No records to display',
jsonReader: {
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: false,
Id: "0"
},
autowidth: true,
multiselect: false,
}).navGrid('#pager', { edit: false, add: true, del: true, search: true, refresh: true },
{
// edit options
zIndex: 100,
url: '/Home/Edit',
closeOnEscape: true,
closeAfterEdit: true,
recreateForm: true,
afterComplete: function (response) {
if (response.responseText) {
alert(response.responseText);
}
}
},
{
// add options
zIndex: 100,
url: "/Home/Create",
closeOnEscape: true,
closeAfterAdd: true,
afterComplete: function (response) {
if (response.responseText) {
alert(response.responseText);
}
}
},
{
// delete options
zIndex: 100,
url: "/Home/Delete",
closeOnEscape: true,
closeAfterDelete: true,
recreateForm: true,
msg: "Are you sure you want to delete this task?",
afterComplete: function (response) {
if (response.responseText) {
alert(response.responseText);
}
}
});
});
What is the problem ? Where am I wrong?

Problem was solved.
Change this:
<link href="~/Content/jquery.jqGrid/ui.jqgrid.css" rel="stylesheet" />
<link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />
<script src="~/Scripts/jquery-1.9.1.min.js"></script>
<script src="~/Scripts/jquery-ui-1.10.4.min.js"></script>
<script src="~/Scripts/i18n/grid.locale-ru.js"></script>
<script src="~/Scripts/jquery.jqGrid.min.js"></script>
<script src="~/Scripts/Billboard.js"></script>
on:
<link href="#Url.Content("~/Content/jquery.jqGrid/ui.jqgrid.css")" rel="stylesheet" />
<link href="#Url.Content("~/Content/themes/base/jquery-ui.css")" rel="stylesheet" />
<script src="#Url.Content("~/Scripts/jquery-1.9.1.min.js")"></script>
<script src="#Url.Content("~/Scripts/jquery-ui-1.10.4.min.js")"></script>
<script src="#Url.Content("~/Scripts/i18n/grid.locale-en.js")"></script>
<script src="#Url.Content("~/Scripts/jquery.jqGrid.min.js")"></script>
<script src="#Url.Content("~/Scripts/Billboard.js")"></script>

Related

Send Variable from AJAX table to ASP.NET MVC Controller

I understand the topic is relatively common, but I've spent a LONG time trying to solve this issue with pre-existing posts and I have come up with no luck to solving my issue.
I have got a Homepage with a small database of "Safes", When a user clicks on one of the safes, it should take them to the "Items" Database view and show ONLY the items of the safe they clicked on. However, instead it shows no results? (I have got the items table to display ALL results, so I know it is not an issue with the database). More baffling is that the "data" I wish to use as the filter does show properly in the URL, so that should be fine too?
Any help would be MUCH appreciated... Thanks in advance peeps! :)
$(document).ready(function () {
var oTable = $('#CBR').DataTable({
"ajax": {
"url": '/Home/GetSafe',
"type": "get",
"datatype": "json"
},
"columns": [
{ "data": "Safe_ID", "autoWidth": true },
{ "data": "Department_ID", "autoWidth": true },
{
"data": "Safe_ID", "width": "50px", "render": function (selectedSafe) {
$.ajax({
url: '/Home/GetSafeItems',
dataType: "json",
data: { selectedSafe: selectedSafe },
type: "GET",
success: function (data) {
if (data.success) {
alert(data.message);
}
},
error: function (xhr) {
alert(selectedSafe);
}
});
return 'Open Safe';
}
}
]
})
HOMEPAGE VIEW (above)
public ActionResult GetSafeItems(string selectedSafe)
{
using (CBREntities2 dc = new CBREntities2())
{
var safeItem = dc.Items.Where(a => a.Safe_ID == selectedSafe).Select(s => new {
Serial_Number = s.Serial_Number,
Safe_ID = s.Safe_ID,
Date_of_Entry = s.Date_of_Entry,
Title_subject = s.Title_subject,
Document_Type = s.Document_Type,
Sender_of_Originator = s.Sender_of_Originator,
Reference_Number = s.Reference_Number,
Protective_Marking = s.Protective_Marking,
Number_recieved_produced = s.Number_recieved_produced,
copy_number = s.copy_number,
Status = s.Status,
Same_day_Loan = s.Same_day_Loan
}).ToList();
// var safeItems = dc.Items.Where(a => a.Safe_ID).Select(s => new { Safe_ID = s.Safe_ID, Department_ID = s.Department_ID, User_ID = s.User_ID }).ToList();
return Json(new { data = safeItem }, JsonRequestBehavior.AllowGet);
}
}
Controller (above)
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Items</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<link rel="stylesheet"
href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" />
<link href="~/Content/themes/base/jquery-ui.min.css" rel="stylesheet" />
</head>
<body>
<div style="width:90%; margin:0 auto" class="tablecontainer">
<a class="popup btn btn-primary" href="/home/SaveItem/0" style="margin-
bottom:20px; margin-top:20px">Add new Item </a>
<table id="CBR-Item">
<thead>
<tr>
<th>Serial Number</th>
<th>Safe ID</th>
<th>Date of Entry</th>
<th>Title/Subject</th>
<th>Document type</th>
<th>Sender of Originator</th>
<th>Reference Number</th>
<th>Protective Marking</th>
<th>Number recieved/produced</th>
<th>Copy number</th>
<th>Status</th>
<th>Same-Day Loan</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
</table>
</div>
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
<script src="~/Scripts/jquery-ui-1.12.1.min.js"></script>
<script>
$(document).ready(function () {
var oTable = $('#CBR-Item').DataTable({
"ajax": {
"url": '/Home/GetSafeItems',
"type": "get",
"datatype": "json"
},
"columns": [
{ "data": "Serial_Number", "autoWidth": true },
{ "data": "Safe_ID", "autoWidth": true },
{ "data": "Date_of_Entry", "autoWidth": true },
{ "data": "Title_subject", "autoWidth": true },
{ "data": "Document_Type", "autoWidth": true },
{ "data": "Sender_of_Originator", "autoWidth": true },
{ "data": "Reference_Number", "autoWidth": true },
{ "data": "Protective_Marking", "autoWidth": true },
{ "data": "Number_recieved_produced", "autoWidth": true },
{ "data": "copy_number", "autoWidth": true },
{ "data": "Status", "autoWidth": true },
{ "data": "Same_day_Loan", "autoWidth": true },
{
"data": "Serial_Number", "width": "50px", "render": function (data) {
return '<a class="popup" href="/home/SaveItem/' + data + '">Edit</a>';
}
},
{
"data": "Serial_Number", "width": "50px", "render": function (data) {
return '<a class="popup" href="/home/DeleteItem/' + data + '">Delete</a>';
}
}
]
})
$('.tablecontainer').on('click', 'a.popup', function (e) {
e.preventDefault();
OpenPopup($(this).attr('href'));
})
function OpenPopup(pageUrl) {
var $pageContent = $('<div/>');
$pageContent.load(pageUrl, function () {
$('#popupForm', $pageContent).removeData('validator');
$('#popupForm', $pageContent).removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse('form');
});
$dialog = $('<div class="popupWindow" style="overflow:auto"></div>')
.html($pageContent)
.dialog({
draggable: false,
autoOpen: false,
resizable: false,
model: true,
title: 'Popup Dialog',
height: 550,
width: 600,
close: function () {
$dialog.dialog('destroy').remove();
}
})
$('.popupWindow').on('submit', '#popupForm', function (e) {
var url = $('#popupForm')[0].action;
$.ajax({
type: "POST",
url: url,
data: $('#popupForm').serialize(),
success: function (data) {
if (data.status) {
$dialog.dialog('close');
oTable.ajax.reload();
}
}
})
e.preventDefault();
})
$dialog.dialog('open');
}
})
</script>
Main safe View (above)
I have not inlcuded the safe view as that element works usually without the filter and is calling to the controller method. But can upload if needed.
Amendment: I have almost solved the post issue... but the post won't actually reach the controller (it just keeps tripping the error value in the code Below)
{
"data": "Safe_ID", "width": "50px", "render": function (data) {
return '<a class="safeLink" href="/home/safeItems/' + data + '">Open Safe</a>';
// return { selectedSafe: selectedSafe }
}
}
]
})
$('.tablecontainer').on('click', 'a.safeLink', function (e) {
e.preventDefault();
var whatWhat = "SEC-1000";
var selectedSafeZZ = { theSafe: whatWhat };
$.ajax({
url: '/Home/GetSafeItems',
data: JSON.stringify(selectedSafeZZ),
contentType: "application/json; charset=utf-8;",
type: "POST",
success: function (data) {
alert(data);
},
error: function (xhr) {
alert("Boohooo");
}
});
Your ajax call has nothing to do with anchor tag link. So do you have any method in home controller which returns data to view like viewresult.?
Can you paste your complete controllers code

Asp.Net MVC jqgrid is not displaying my data

I am trying to fill a jqgrid. The grid is rendered but no data is displayed. I know my controller -- as called through a standard ajax function -- is working. It returns the data I'd expect.
How do I verify that jqgrid is returning the same data and what am I doing incorrectly that is not allowing the data to be dispayed?
jqgrid:
<script type="text/javascript">
jQuery(document).ready(function() {
$.ajaxSetup({ cache: false });
var rvtoken = $("input[name='__RequestVerificationToken']").val();
var ModuleId = #Dnn.ModuleContext.ModuleId;
var TabId = #Dnn.ModuleContext.TabId;
$('#grid').jqGrid({
url: '/DesktopModules/MVC/CW.GridTest/Item/getArtists2',
datatype: 'json',
mtype: 'POST',
contentType: 'application/json',
loadBeforeSend: function(jqXHR) {
jqXHR.setRequestHeader('ModuleId', ModuleId);
jqXHR.setRequestHeader( 'TabId', TabId);
jqXHR.setRequestHeader('RequestVerificationToken', rvtoken);
},
colNames: ['ArtistID', 'ArtistName', 'City'],
colModel: [
{ name: 'ArtistID', index: 'ArtistID', width: 80, align: 'left', editable: false },
{ name: 'Name', index: 'ArtistName', width: 120, align: 'left', editable: true },
{ name: 'Location', index: 'City',width: 60,align: 'left',editable: true}
],
loadError: function (jqXHR, textStatus, errorThrown) {
alert('HTTP status code: ' + jqXHR.status + '\n' +
'textStatus: ' + textStatus + '\n' +
'errorThrown: ' + errorThrown);
alert('HTTP message body (jqXHR.responseText): ' + '\n' + jqXHR.responseText);
},
loadOnce: true,
autoencode: true,
height: '100%',
rowNum: 10,
emptyrecords: 'No records',
sortname: 'ArtistID',
sortorder: 'desc',
viewrecords: true,
caption: 'Artists',
width: 300,
gridview: true,
jsonReader:
{
total: 'total',
page: 'page',
records: 'records',
root: 'rows',
repeatitems: false,
id: 'ArtistID'
}
});
jQuery("#grid").jqGrid('navGrid', '#pager', { edit: false, add: false, del: false });
});
</script>
<div>
<table id="grid"></table>
<div id="pager"></div>
</div>
Returned data from standard ajax:
{
"total":100,
"page":99,
"records":6,
"rows":"[
{\"ArtistID\":1,\"ArtistName\":\"Clayton Knight\",\"City\":\"Tigard\"},
{\"ArtistID\":2,\"ArtistName\":\"Corral Creek Bluegrass\",\"City\":\"Sherwood\"},
{\"ArtistID\":3,\"ArtistName\":\"Never Strangers Band\",\"City\":\"Portland\"},
{\"ArtistID\":5,\"ArtistName\":\"The Hillwilliams\",\"City\":\"Tigard\"},
{\"ArtistID\":7,\"ArtistName\":\"Bobo and the Bobbettes\",\"City\":\"Ellensburg\"},
{\"ArtistID\":27,\"ArtistName\":\"Bobo 5\",\"City\":\"Ellensburg\"}
]"
}
It was my controller. Not that it wasn't working but that it wasn't returning what I thought it should be. I was deserializing the data table for the "rows" element, and then deserializing the entire element again. So, the controller wasn't return a json string that jqgrid could actually work with.
It's all working now...
public String getArtists2()
{
using (var ac = new ArtistListingController())
{
ac.Gets();
ac.LoadDatatable();
DataView view = new DataView(ac.Datatable);
DataTable dt = view.ToTable(false, "ArtistID", "ArtistName", "City");
var jsonData = new
{
page=1,
total = 1, // (ac.RecordCount + rows - 1) / rows,
records = ac.RecordCount,
rows = dt //JsonConvert.SerializeObject(dt)
};
return JsonConvert.SerializeObject(jsonData);
}
}
Returning:
{
"page":1,
"total":1,
"records":6,
"rows":[
{
"ArtistID":1,
"ArtistName":"Clayton Knight",
"City":"Tigard"
},
{
"ArtistID":2,
"ArtistName":"Corral Creek Bluegrass",
"City":"Sherwood"
},
{
"ArtistID":3,
"ArtistName":"Never Strangers Band",
"City":"Portland"
},
{
"ArtistID":5,
"ArtistName":"The Hillwilliams",
"City":"Tigard"
},
{
"ArtistID":7,
"ArtistName":"Bobo and the Bobbettes",
"City":"Ellensburg"
},
{
"ArtistID":27,
"ArtistName":"Bobo 5",
"City":"Ellensburg"
}
]
}

Events not appearing when moving from an empty month

If I move from a month with events to a month without events and then back again, my events are not re-appearing. Moving between months with events is working fine. I have to refresh the page to get them to come back. Here is my code and I just cannot see anything wrong...
$("#datepicker").fullCalendar({
header: {
left: 'prev,next,cbRefresh',
center: 'title',
right: ''
},
height: 750,
firstDay: 1,
weekNumbers: true,
editable: false,
eventLimit: true,
displayEventTime: false,
dayClick: function(seldate,jsEvent,view) {
window.location.href="multiple?dt="+seldate.format();
},
eventClick: function(evt,jsEvent,view) {
if(evt.id) {
window.location.href="details?id="+evt.id+"&dt="+evt.start.format();
}
},
events: {
url: servicePath+"calendar.php",
type: 'GET',
data: function() {
var theDate=$("#datepicker").fullCalendar('getDate');
return {
t: 'load',
uid: uid,
mon: theDate.month()+1
}
},
error: function(){
displayError("Events error: " +item.ErrorMessage);
}
},
eventRender: function(evt,ele,view) {
$(ele).each(function(){
$(this).attr("data-num",evt.start.format("YYYY-MM-DD"));
$(this).attr("data-worked",evt.worked);
$(".fc-title",this).attr("title",evt.activity);
});
},
eventAfterAllRender: function(view) {
if(view.name=="month") {
for(cDay=view.start.clone(); cDay.isBefore(view.end); cDay.add(1,'day')) {
var ttl=0;
var dateNum=cDay.format('YYYY-MM-DD');
$(".fc-event-container").find('.fc-event[data-num="'+dateNum+'"]').each(function(){
var currentWorked=$(this).attr("data-worked");
if(currentWorked) {
ttl+=parseInt(currentWorked);
}
});
//display the total and relevant buttons
if(ttl>0) {
var footer=$('.fc-day[data-date="'+dateNum+'"]').find(".fc-cell-footer");
$(footer).append('<a title="Delete all" class="btn btn-xs" href="delete?dt='+dateNum+'">'+
'<span class="glyphicon glyphicon-trash"></span></a>'+
'<a title="Copy" class="btn btn-xs" href="copy?dt='+dateNum+'">'+
'<span class="glyphicon glyphicon-copy"></span></a>'+
'<a title="List" class="btn btn-xs" href="list?dt='+dateNum+'">'+
'<span class="glyphicon glyphicon-th-list"></span></a>');
$(footer).append('<span class="ttlHours">Hours: '+buildTime(ttl)+'</span>');
}
}
}
},
dayRender: function(date,cell) {
var theDate=moment(date).format("YYYY-MM-DD");
$(cell).css("vertical-align", "bottom");
$(cell).append('<div class="fc-cell-footer"></div>');
},
customButtons: {
cbRefresh: {
text: 'Refresh',
click: function() {
$("#datepicker").fullCalendar("destroy");
buildCalendar();
}
}
}
});
Have even tried stripping the code back to the very basics and still not working. I do know the 'events: data' is being fired every time as I have it set to email me (while testing).
$("#datepicker").fullCalendar({
header: {
left: 'prev,next,cbRefresh',
center: 'title',
right: ''
},
height: 750,
firstDay: 1,
weekNumbers: true,
editable: true,
eventLimit: true,
displayEventTime: false,
events: {
url: servicePath+"calendar.php",
type: 'GET',
data: function() {
var theDate=$("#datepicker").fullCalendar('getDate');
return {
t: 'load',
uid: uid,
mon: theDate.month()+1
}
},
error: function(){
displayError("Events error: " +item.ErrorMessage);
}
},
customButtons: {
cbRefresh: {
text: 'Refresh',
click: function() {
$("#datepicker").fullCalendar("destroy");
buildCalendar();
}
}
}
});
Sounds like the URL you provide is filtering on the events that the calendar should show. Try something simple as:
$("#calendar").fullCalendar({
events: {
url: 'getcalendar.php',
type: 'POST',
data: {
},
success : function(response){
console.log("Updated events: "+response.length);
}
}
});
Php:
<?php
$start = $_POST['start'];
$end = $_POST['end'];
$query = mysqli(X,"SELECT * FROM calendar startdate >= '$start' AND enddate <= '$end'");
echo json_encode(mysqli_fetch_array($query,MYSQLI_ASSOC));
?>

Disable FullCalendar call Ajax

I'm here again.
I'm using FullCalendar, I use the property "events" to get the values ​​of the agenda and show to the user.
Wanted to know if you have some form of before firing this event, let the FullCalendar disabled until the return to Ajax request?
This is code:
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'agendaWeek,agendaDay'
},
defaultView: 'agendaDay',
editable: true,
allDaySlot: false,
selectable: true,
slotMinutes: 10,
firstHour: 7,
minTime: '7:00am',
slotEventOverlap: false,
events: '/Agenda/GetDiaryEvents/',
eventClick: function (calEvent, jsEvent, view) {
alert('You clicked on event id: ' + calEvent.id
+ "\nSpecial ID: " + calEvent.someKey
+ "\nAnd the title is: " + calEvent.title
+ "\nMédico: " + calEvent.Medico);
}
});
tks
I don't think there is a single method to disable the calendar completely. But if you are just trying to restrict any user interaction with the calendar you can set the editable, droppable, and selectable attributes to false before the ajax call, then toggle them back in your success/complete ajax callback. This should prevent the user from manipulating anything on the calendar during that time....
The solution I found was this and developed below.
Before calling the events of Ajax, you create a Dialog JQuery without any button, and after it's all ok, it closes automatically.
I want to implement if it goes to show another error message, but as there is, is pretty easy to do ...
<script>
$(document).ready(function () {
$("#loading").dialog({
modal: true,
autoOpen: false,
closeOnEscape: false
});
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'agendaWeek,agendaDay'
},
defaultView: 'agendaDay',
editable: true,
allDaySlot: false,
selectable: true,
slotMinutes: 30,
firstHour: 7,
minTime: '7:00am',
slotEventOverlap: false,
/*events: '/Agenda/GetDiaryEvents/',*/
events: {
url: '/Agenda/GetDiaryEvents/',
type: 'GET',
data: {
custom_param1: 'something',
custom_param2: 'somethingelse'
},
beforeSend: function() {
$("#loading").parent().children().children('.ui-dialog-titlebar-close').hide();
$("#loading").dialog('open');
},
success: function () {
},
error: function() {
alert('there was an error while fetching events!');
},
complete: function () {
$("#loading").dialog('close');
},
},
eventClick: function (calEvent, jsEvent, view) {
alert('You clicked on event id: ' + calEvent.id
+ "\nSpecial ID: " + calEvent.someKey
+ "\nAnd the title is: " + calEvent.title
+ "\nMédico: " + calEvent.Medico);
}
});
$('#datepicker').datepicker({
inline: true,
onSelect: function (dateText, inst) {
var d = new Date(dateText.substr(3, 2) + "/" + dateText.substr(0, 2) + "/" + dateText.substr(6, 4));
$('#calendar').fullCalendar('gotoDate', d);
},
dateFormat: 'dd/mm/yy',
dayNames: ['Domingo', 'Segunda', 'Terça', 'Quarta', 'Quinta', 'Sexta', 'Sábado'],
dayNamesMin: ['D', 'S', 'T', 'Q', 'Q', 'S', 'S', 'D'],
dayNamesShort: ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sáb', 'Dom'],
monthNames: ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'],
monthNamesShort: ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez'],
nextText: 'Próximo',
prevText: 'Anterior'
});
$('.fc-button-prev').click(function () {
alert('prev is clicked, do something');
var view = $('#calendar').fullCalendar('getView');
alert("The view's title is " + view.title);
alert("start: " + view.start);
alert("start: " + view.end);
});
$('.fc-button-next').click(function () {
alert('nextis clicked, do something');
});
});
</script>
<div class="linha">
<div id="datepicker"></div>
</div>
<div class="linha">
<div id='calendar'></div>
</div>
<br />
<br />
<br />
<br />
<div id="loading" title="Processando...">
<p>Aguarde buscando dados...</p><br /><br />
<img src="#Url.Content("~/Content/images/icon_48x48_ajax.png")" title="Carregando" />
<br /><br />
</div>

jqgrid implementation using JSOn and asp.net

Last time, I asked similar question. Now I tried to put the jqgrid together to work. However, I tried to bring the grid but the data is not loading.
here are the two files
GetData.aspx
<%# Page Language="C#" %>
<%# Import Namespace="System.Web.Script.Serialization"%>
<%# Import Namespace="System.Collections.ObjectModel"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(GetData());
Response.End();
//Response.Write ("Data is being loaded");
}
protected string GetData()
{
var list = new Collection<People>
{
new People {Id = 1, Name = "John", Gender = 1, IsClosed = false},
new People {Id = 2, Name = "Abel", Gender = 1, IsClosed = false},
new People {Id = 3, Name = "Aaron", Gender = 1, IsClosed = true},
new People {Id = 4, Name = "Tsion", Gender = 2, IsClosed = true},
new People {Id = 5, Name = "Mussie", Gender = 2, IsClosed = true}
};
return GridData(1, 1, list.Count, list);
}
public string GridData(int noOfPages, int startPage, int noOfRecords, Collection<People> list)
{
var gridData = new
{
total = noOfPages,
page = startPage,
records = noOfRecords,
rows = list,
};
var jsonSerializer = new JavaScriptSerializer();
return jsonSerializer.Serialize(gridData);
}
public class People
{
public People()
{
Name = string.Empty;
Id = 0;
Gender = 0;
IsClosed = false;
}
public string Name { get; set; }
public int Id { get; set; }
public int Gender { get; set; }
public bool IsClosed { get; set; }
}
public enum Oper
{
edit=1,
del=2,
add=3
}
</script>
</html>
JQExample.aspx
<%# Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head id="Head1" runat="server">
<title>JqGrid</title>
<link href="themes/redmond/jquery-ui-1.8.2.custom.css" rel="stylesheet" type="text/css" />
<link href="themes/ui.jqgrid.css" rel="stylesheet" type="text/css" />
<script src="Scripts/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="Scripts/jquery.jqGrid.js" type="text/javascript"></script>
</head>
<body>
<%-- <form id="form1">--%>
<table id="jsonmap">
</table>
<div id="pjmap">
</div>
<script type="text/javascript">
jQuery("#jsonmap").jqGrid({
url: 'GetData.aspx',
datatype: 'json',
colNames: ['ID', 'Name','Active','Gender'],
colModel: [{
name: 'id',
index: 'id',
width: 35,
editable: false,
editoptions: {
readonly: true,
size: 10
}},
{
name: 'name',
index: 'name',
width: 150,
align: "left",
editable: true,
size: 100
},
{
name: 'isClosed',
index: 'isClosed',
width: 100,
align: 'left',
editable: true,
edittype: "checkbox",
editoptions: {
value: "true:false",
formatter: "checkbox"
}},
{
name: 'gender',
index: 'gender',
width: 100,
formatter:'select',
editable: true,
edittype: "select",
editoptions: {value: "0:select;1:male;2:female"}
}],
rowNum: 10,
rowList: [2, 5, 10, 15],
pager: '#pjmap',
sortname: 'id',
sortorder: "desc",
viewrecords: true,
jsonReader: {
repeatitems: false
},
width: 600,
caption: 'First jqGrid',
height: '100%',
editurl: 'GetData.aspx'
});
jQuery("#jsonmap").navGrid("#pjmap", {
edit: true,
add: true,
del: true
},
{
closeAfterEdit: true,
reloadAfterSubmit: false
},
{
closeAfterAdd: true,
reloadAfterSubmit: false
},
{
reloadAfterSubmit: false
});
</script>
<table id="Jqgrid" width="100%">
</table>
<div id="pager"></div>
</form>
</body>
</html>
Now I would like to change data to be displayed dynamically using ADO.net.
Thank you sir. It worked now.
I want to change to get data dynamically which is change the data source in GetData.aspx and format the colNames and ColModel in JQExample.aspx file:
$(document).ready(function () {
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
//url: "GetData.aspx",
datatype: 'json',
success: function (result) {
// colD = result.colData;
// colN = result.colNames;
var colM = result.colModel;
//alert(result.colModel);
jQuery("#jsonmap").jqGrid
(
{
jsonReader: { repeatitems: false, cell: "",id: "0" },
//url: "GetData.aspx",
datatype: 'json',
mtype: 'POST',
colModel: colM,
data: colD.rootVar,
ColNames: colN,
ColModel: ColM,
height: "auto",
gridview: true,
pager: '#pager',
rowNum: 5,
rowList: [5, 10, 20, 50],
viewrecords: true,
loadComplete: function (data) {
alert('loaded completely');
},
loadError: function () {
alert('error');
}
});
},
error: function (x, e) {
alert(x.readyState + ' ' + x.status + e.msg);
}
});
The following code should be replaced by ADO.Net connection in GetData.aspx
var list = new Collection<People>
{
new People {Id = 1, Name = "John", Gender = 1, IsClosed = false},
new People {Id = 2, Name = "Abel", Gender = 1, IsClosed = false},
new People {Id = 3, Name = "Aaron", Gender = 1, IsClosed = true},
new People {Id = 4, Name = "Tsion", Gender = 2, IsClosed = true},
new People {Id = 5, Name = "Mussie", Gender = 2, IsClosed = true}
};
Would you please tell me what to do in the next step?
I do have server end data source (SQL server). so should I write a select statement to get the total number of records, pages and order by (sorting) fearures to display in the grid? If so would you please give sample code which has top, limit and order by?
Is there anything missing in the above codes to get the data dynamically?
There are several things wrong with your implementation especially if you want it to be editable but just to load the data you need to fix your column mappings. They do not match. Also, I believe it's case sensitive so you need to change the colNames to below and update colModel to match those names/case:
colNames: ['Id', 'Name','IsClosed','Gender']

Resources