Problem binding jqGrid in ASP.NET - asp.net

I am new to using jqGrid and jquery.I am not able to bind my json data which I retrive from the webmethod onto the jqGrid.
I have also used firebug to cross verify and i am receiving data from it. Some help regarding this will be great. I would aslo like to know if any other references needs to be added.
following is the code that I have implemented.
PAGE METHOD
[WebMethod]
public static string GetData()
{
Customer Cone = new Customer();
Customer Ctwo = new Customer();
Cone.CustomerID = "100";
Cone.CustomerName = "abc";
Ctwo.CustomerID = "101";
Ctwo.CustomerName = "xyz";
List<Customer> lstCustomer = new List<Customer>();
lstCustomer.Add(Ctwo);
lstCustomer.Add(Cone);
JavaScriptSerializer jsonSerz = new JavaScriptSerializer();
string serializedData = jsonSerz.Serialize(lstCustomer);
return serializedData;
}
client side coding
<script type="text/javascript" src="jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="jquery.jqGrid.min.js"></script>
<script type="text/javascript">
function GetData() {
alert('Inside GetData');
var data = PageMethods.GetData(OnSuccess, OnFailed);
}
function OnFailed(error) {
alert('Failed');
alert(error.get_message());
}
function OnSuccess(data) {
alert(data);
}
$(document).ready(function() {
$('#submit').click(function() {
alert('Button Clicked');
$('#list').jqGrid({
url: 'http://localhost:1405/WebSite1/Default.aspx/GetData',
data: '{}', // For empty input data use "{}",
dataType: 'local',
type: 'POST',
contentType: "application/json; charset=utf-8",
colNames: ['CustomerID', 'CustomerName'],
colModel: [
{ name: 'CustomerID', index: 'CustomerID', width: 80,
align: 'left', editable: false },
{ name: 'CustomerName', index: 'CustomerName', width: 120,
align: 'left', editable: true}],
pager: $('#pager'),
rowNum: 5,
rowList: [10],
sortname: 'CustomerID',
sortorder: 'desc',
viewrecords: true,
width: 300
});
});
});
</script>
AND HTML code
<asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true" runat="server">
</asp:ScriptManager>
<input type="button" id="submit" value="Fetch" title="Fetch"
onclick="javascript:GetData()" />
<table id="list">
</table>
<div id="pager">
</div>

First of all I recommend you to play a little with another working code which you can download here (see more information here). More links to another examples you can find here.
I try to describe some problems in your current code.
You use 'http://localhost:1405/WebSite1/Default.aspx/GetData' as the url. You shold better use only pathes like '/WebSite1/Default.aspx/GetData' or 'WebSite1/Default.aspx/GetData' or you can easy receive same origin policy problem.
You should use ASMX service instead of placing the code inside of ASPX page (Default.aspx/GetData). You should just add new item to your ASP.NET solution and choose Web Serice template. The corresponding code template will be added for you and web.config will be modified. In the same way you can place WCF service inside your ASP.NET project. The step is independ on the technology which you use (WebForms, ASP.NET MVC and so on).
Instead of manual JSON serialisation with respect of JavaScriptSerializer you should define [ScriptMethod(ResponseFormat = ResponseFormat.Json)] attriute to your method and return an object from the web method (like List<Customer> in your case). The JSON serialization will be done automatically for you.
You use dataType: 'local' which is wrong parameter for jqGrid. Correct parameter will be datatype:'json' (datatype instead of dataType and 'json' to make the request to the server).
Instead of type: 'POST' you should use mtype: 'POST'.
Instead of contentType: "application/json; charset=utf-8" you should use ajaxGridOptions: { contentType: "application/json" }.
The usage of data: '{}' is also wrong. Probably you try to use data parameter of jQuery.ajax like with dataType parameter. In jqGrid you should use pastData instead of data and the data parameter must be an array and has another meaning. I recommand you to look at the code of the example (see reference at the begin of my answer).
You should not place $('#list').jqGrid({...}); inside of click handle. The problem is that the code make some initializations of jqgrid and then fill the grid. What you probaly want is creating the grid only once and then refreshing it with another input data probaby (I am not sure that it is so). So you should move $('#list').jqGrid({...}); inside of $(document).ready(function() {...};. If needed you can use $('#list').trigger("reloadGrid") inside of the click event handle. Alternatively you can use GridUnload to destroy the existing grid before creating it new.
I can continue, but my main recommendation is to examine another examples and use ASMX or WCF service which provide the data for jqGrid.

Entire grid binding event is called before your page method.
You have put it under document.Ready event. Try calling it from the button click event.
I am not sure but there should be some way to bind json data to Jquery grid on client side without using the URL part.
try mapping "data:" to some Json value.

Related

jQuery datatables customizable columns (asp.net usercontrol)

net webforms application.
In my .aspx page Im using jQuery datatables and its gets data using ajax.
In my jQuery datatables I have some configuration for setting up my columns:
'columnDefs': [{
'targets': 0,
'searchable': false,
'orderable': false,
'className': 'dt-body-center',
'render': function(data, type, full, meta) {
//return '<input type="checkbox">';
if (data == "false") {
return '<input type="checkbox" class="styled green">';
} else {
return '<input type="checkbox" class="styled green" checked="' + data + '">';
}
}
}],
I have a requirement to move this jQuery datatable to an usercontrol so it can be reusable on other parts of the web application but I should be able to let the control know what columns to hide.
I was thinking on sending from server other property in my json, an array maybe named HideCols that has the index of the columns that I want to hide and then apply with jQuery some code to hide them.
Im getting the table data like this:
"fnServerData": function(sSource, aoData, fnCallback) {
aoData.push(
{ name: "filter", value: filterVal }
);
$.ajax({
"dataType": 'json',
"contentType": "application/json; charset=utf-8",
"type": "GET",
"url": sSource,
"data": aoData,
"success": function(msg) {
// here I get my json table data from server
var json = jQuery.parseJSON(msg.d);
fnCallback(json);
// here I can do my jQuery code to hide columns
if(json.HideCols != null)
{
}
}
});
}
Other way would be great if I can send from server the columnDefs configuration but I guess its going to be more tricky.
Any clue?
I have implemented the dynamic columnDefs (colModel) functionality with jqGrid. You may read the post here jqgrid-dynamic-reading-of-colmodel-and-colnames-from-codebehind-of-aspx
You may get the basic idea of generating dynamic columnDefs (xxx_colModel in above post) and ajaxData (xxx_Data in above post) from code-behind and implement it in your way. Set properties of columns to hide in the dynamically generated columnDefs.
As regard to your approach of hiding the columns:
I was thinking on sending from server other property in my json, an array maybe named HideCols that has the index of the columns that I want to hide and then apply with jQuery some code to hide them.
You may add another property to top level of JSON along with xxx_colModel and xxx_Data say xxx_HiddenCols and store csv column IDs e.g. 2,8,9
Then on the client side, after the grid is initialized, you may use for loop to process each column to hide e.g.
var colArray = xxx_HiddenCols.split(',');
for (var i = 0; i < colArray.length; i++) {
table.column( colArray[i] ).visible( false );
}

Accessing div in view from controller

In my layout page I've got this html:
<div id="ajax-loading" class="global-loading-image" runat="server">
<img src="/content/travelbill/img/small-loading-image.gif"/>
</div>
Which is a loading-symbol. I want it to show when my code is doing its business.
I've read on other threads here on Stackoverflow that if you use runat="server", you are supposed to be able to access the div in the controller. Like so:
ajax-loading.Visible = true;
EditTravelBillViewModel model = this.travelBillService.GetTravelBill(travelBillId);
model.StageOfProcess = (int)TravelBillStageOfProcessEnum.APPROVED;
this.travelBillService.Update(model, true);
ajax-loading.Visible = false;
return RedirectToAction("GetTravelBillsPerCompany");
But I get the error that the loading and the ajax do not exist in the current context. What am I doing wrong?
That was in the old ASP.NET pages. In ASP MVC you don't have a ViewState, isPostBack or runat="server" you can pass variables from the controller to the view using ViewBag and ViewData like:
Controller:
ViewBag.Name = "My Name";
ViewData["Name"] = "My Name";
View:
#ViewBag.Name
#ViewData["Name"]
I don't think you need to do that. You can have a action that do the task that you need to get done and with JavaScript request that action via AJAX. You can then with JavaScript show and hide the loading as you wish:
function LoadAjax(containerId, url, params){
//Set loading in container
$(containerId).html('<img src="loading.gif" alt="loading"/>');
//Do the request
$.ajax({
type: 'POST',
dataType: "html",
url: url,
data: params,
success: function(data){
// show response inside container (removes loading)
$(containerId).html(data);
},
error: function( jqXHR, textStatus, errorThrown){
// show error inside container (removes loading)
$(containerId).html(textStatus);
}
});
}
While the page is loading it will display the loading image. You will need Jquery to use my code. Hope it helps.

how to delete selected records of jqgrid in asp.net c#

can anyone help in deleting selected records of jqgrid in asp.net c# for the following code
<script type="text/javascript">
var x = screen.width;
$(document).ready(function() {
jQuery("#table1").jqGrid({
url: 'griddata.aspx/DepartmentData?id=1',
datatype: 'json',
mtype: 'GET',
colNames: ['Department', 'Dept Code', 'Contact Person', 'Contact Phone','Contact Email'],
colModel: [
{ name: 'Department', index: 'Department', width: 55 },
{ name: 'Dept Code', index: 'Dept Code', width: 90 },
{ name: 'Contact Person', index: 'Contact Person', width: 40, align: 'center' },
{ name: 'Contact Phone', index: 'Contact Phone', width: 40, align: 'center' },
{ name: 'Contact Email', index: 'Conatct Email', width: 40, align: 'center' }],
pager: '#pager1',
rowNum: 15,
rowList: [10, 20, 30],
sortname: 'Department',
sortorder: "desc",
loadonce: true,
loadtext: "Loading....",
shrinkToFit: true,
multiselect: true,
emptyrecords: "No records to view",
width: x - 40,
height: 230,
rownumbers: true,
caption: 'DepartmentTable'
});
jQuery("#table1").jqGrid('navGrid', '#pager1', { edit: true, add: true, del: true });
});
</script>
(Might be time to start moving this conversation from comments to an answer...)
I'm not 100% familiar with this particular functionality in jqGrid (as I said in a comment, its own documentation has a hard time keeping up with its development), but essentially there should be one of two things that the "delete" functionality is looking for:
A URL to send a pre-determined delete request. Likely a GET request with some parameters on the query string, though that's not certain. This URL may be highly configurable. You'll need to find where/how to configure it (unless you can point me to the documentation/tutorial you're using and perhaps I can help from there).
A client-side event handler for the deletes. This would likely be something to which you'd attach an inline function in your JavaScript code. This function, for your needs, will probably just be an AJAX call (via jQuery, naturally) to a server-side resource of your design/choosing which would handle the deletes.
From my past experience with jqGrid, and from your comments so far, it sounds like the first option is what it's looking for. Somewhere in its initialization jqGrid needs you to set a URL to which it will send deletes. This URL will be of your own design for your server-side code.
That means you also need to create a server-side handler to make this happen. If you're using ASP .NET MVC, this is very easy. A controller action will do the job just fine and can even return JSON very easily if anything needs to be sent back to the client-side. If you're using WebForms, you have two primary options:
Create a new page which has no UI (delete everything but the Page directive from the .aspx file). It would check the incoming parameters, perform the action you need on the server-side (delete the record from the database, most likely), then manually craft a response. You'll want to look into manipulating response headers for this, because it will probably expect the content type to be application-json or something of that nature.
Create an HttpHandler which doesn't have the overhead of an .aspx page (and is a lot more like a controller action in that respect). It would do the same thing, performing the server-side action and all that, and manually crafting a response. (I'm assuming a particular response is expected, such as an indication of success or failure which may be in the form of an actual server error such as a 500.)
Your jqGrid initializer would set some property which configures the URL it uses to send delete requests to the server. This would have to include the ID of the row being deleted, of course. Essentially, you have a lot of manual control over what's going on. It's not really plug-and-play, you have to write and understand the code.
Edit: If you're doing the client-side delete on the server-side then you don't need a lot of jqGrid involvement here. You'd just have an ASP .NET button which posts back to the server, deletes the record, and re-binds the page data (to include the jqGrid data) to the new data set from the server. Keep in mind that this post-back model is not really what jqGrid is meant to use.
You can add a button on the client-side for jqGrid deletes, as demonstrated here (click on "Live Data Manipulation" on the left and then on "Delete Row" to see the example). Then you'd simply write a JavaScript function for that button's click event to handle the delete. Their example does the client-side delete:
$("#dedata").click(function(){
var gr = jQuery("#delgrid").jqGrid('getGridParam','selrow');
if( gr != null )
jQuery("#delgrid").jqGrid('delGridRow',gr,{reloadAfterSubmit:false});
else
alert("Please Select Row to delete!");
});
Of course, you'll need to add to that (as I said in a comment, before the client-side delete in case there's an error on the server) an AJAX call to handle the server-side delete as I'd talked about above. The most straight-forward way would be to use the jQuery .ajax method. This would call your server-side resource (controller action, HttpHandler, or .aspx page) that would handle the server-side delete and return success or failure.
Keep in mind the server-side delete from the database is an entirely separate topic than what you're doing here. It's also very well covered in ADO .NET and LINQ and Entity Framework articles and tutorials all over the internet. Essentially, all you're looking to do there (based on your comments so far) is call a SQL stored procedure from .NET code. Google will yield many results on this.

mvc with ajax post

i have a form which includes list of records. When user clicks edit image on table modal div will show to him. i get this modal div with ajax. Now after changing some fields i am posting it via ajax. I watched to firebug. it sends parameter. But when i debug code in VS method calls but no parameter has been send. i have done it before in other pages. but now i can not. What problem can be here in my code?
C# Code here
[HttpPost]
//[Authorize(Roles = "Operator")]
public ActionResult EditRow(string Name, string SecondName)
{
//code goes here
return Content("Saved");
}
jquery ajax code is here
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: 'EditRow',
data: { Name: "php", SecondName: "MVC" },
dataType: 'html',
success: function (response) {
//some code goes here
}
});
Have you tried to simplify your Ajax call to:
$.ajax({
type: 'POST',
url: 'EditRow',
data: { Name: "php", SecondName: "MVC" },
success: function (response) {
//some code goes here
}
});
If this doesn't work there must be something else in your code that makes your code invalid. Maybe some base controller action filters you forgot to put there or some custom model binders or some other global registration.
Sending complex JSON to server
If you'd like to send complex JSON using the same technique, you can read my blog post and use the simple plugin that will make it possible to send complex JSON objects to Asp.net MVC controller action.

Why do I need to use .d to access data returned by jQuery AJAX?

I've put together some jQuery AJAX code using some tutorials I found on the internet. I'm new to jQuery and want to learn how to do things betters. I have a coworker who put together a beautiful web application using a lot of jQuery.
The thing I'm most confused about here is: why is it necessary to use the ".d" when referring to the response of my web method and what does it stand for?
// ASP.net C# code
[System.Web.Services.WebMethod]
public static string hello()
{
return ("howdy");
}
// Javascript code
function testMethod() {
$.ajax({
type: "POST",
url: "ViewNamesAndNumbers.aspx/hello",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg); // This doesn't display the response.
alert(msg.d); // This displays the response.
} // end success:
}) // end $.ajax
It was added in ASP.NET 3.5’s version of ASP.NET AJAX to prevent you from being vulnerable to this exploit: http://haacked.com/archive/2009/06/25/json-hijacking.aspx
(Answer sourced from http://encosia.com/2009/06/29/never-worry-about-asp-net-ajaxs-d-again/)
Microsoft does this to protect you from a security exploit. See the bottom of This Page for more information.
I guess alert(msg) displays "[object Object]" ?
If so it's because the object which is parsed through window.JSON (which happens under the hood when specifying json as dataType) does really look:
object = {
d: "some data"
}
Check what you are generating in ViewNamesAndNumbers.aspx/hello

Resources