2013年9月24日星期二

Full implementation of ASP.NET using JqGrid

 

article outline

 
      
  •    
         Introduction & using the Scene    
  •   
  •    
         JqGrid of some description    
  •   
  •    
         JqGrid and ASP.NET integration detailed steps    
  •  
 

 

pre- prepare

 

frame structures

 

data to populate

 

data add / delete / change

 

other

 

 

Intro & usage scenarios

 

JqGrid is not a new thing , it is already a well- proven open source data controls it.

 

garden also has some introductory essay , why write this articles do ?

 

because you can not find the full article about JqGrid integration , I mean about the complete start to finish , rather than some of the fragments or introduce some parameters.

 

just seeing an article about the complete this step : http://www.codeproject.com/Articles/609442/Using-JqGrid-in-ASP-NET

 

this article references the article , tells jqGrid and ASP. NET integration .

 

use scene :

 

data many and complex , if you want to display tabular data increased easily check / delete the selected function .

 

JqGrid free, open source , easy to use, is a good choice.

 

 

JqGrid of some description

 
  
       
  • look stylish , fully functional
  •    
  • JS controls used to display and manipulate tabular data
  •    
  • using AJAX way
  •    
  • can be integrated into any server-side technologies such as ASP, JavaServelets, JSP, PHP and so on .
  •    
  • developed by the Trirand Company Tony Tomov .
  •    
  • and ASP.NET integration is very simple
  •   
 
 

JqGrid and ASP.NET integration detailed steps

 
      
  • download JqGrid, add the necessary files to the ASP.NET application ( mainly some Scripts and CSS).
  •   
  • the page you need to use to initialize JqGrid .
  •   
  • binding data < / li>   
  • some other operations, such as CRUD < / span>
  •  
 
    
 

1. Did I mention the first point , you can download at the following address JqGrid and related files

 

http://www.trirand.com/blog/?page_id=6

 

Download get jquery.jqGrid-4.5.2.zip .

 

unzip the file , there are some css and script folders , let's go and see how to use these files.
To better understand , in accordance with international practice I created a demo program : JQGridPOC, to demonstrate the steps and integration with the function .

 

We need to introduce the main document is jQuery, because jqGrid relies on jQuery.

 

specialized in the solution used to create a new folder JQGridReq put JqGrid related files.

 

the first step , add the jQuery file ( I added the jQuery 1.9).

 

the second step, if we want to use jQuery UI related things any ? Yes , CSS files to jQuery's official website to download .

 

the last step , add Jquery-ui-1.9.2.custom.css to the program.

 

Make sure you also add the relevant picture folder, because we may also be used to add a CSS related pictures .

 

This jQuery's things ready.

 

Here again one by one began to add our JqGrid file.

 
      
  1. jquery.jqGrid-4.5.2 \ src \ jquery.jqGrid.js < / em>
  2.   
  3. jquery.jqGrid-4.5.2 \ js \ i18n \ grid.locale-en . js
  4.   
  5. jquery.jqGrid-4.5.2 \ js \ i18n \ grid.locale-cn.js
  6.   
  7. jquery.jqGrid-4.5.2 \ css \ ui.jqgrid.css
  8.  
 

you see above to add locale-en.js/local-en.js files yet ? they are very important , in which you can change some default parameters.

 

Similarly, we also added a CSS file .

 

Now that we have completed the prerequisites .

 

the following figure, you can see that after we add files and folders structure .

 

 

 

let's go . aspx page to add JqGrid it.

 

this simple example project I used a simple case of customer management , use Default.aspx as an example.

 

you need to first of all necessary documents referenced to the head section of the HTML page , as shown below.

 

 

Now you need to do is first placed into the HTML table tag page, give this table specifies a ID jQgridPOC ( this table is that we are going to transform into JqGrid).

 

 

 

 

 

2. pages you need to use to initialize JqGrid.

 

The following will apply this table into JqGrid.

 

ready we will intend to appear in the Grid field , when we initialize the table must bring these fields.

 

we are ready to show that :

 
  
       
  1. UniqueID
  2.    
  3. First Name
  4.    
  5. Last Name
  6.    
  7. City
  8.    
  9. State
  10.    
  11. Address.
  12.   
 
 

You can use the following script to initialize the HTML table grid.

 

 

code snippet :

 
      ; << span style = "color: # 800000;"> script >  
 
   ; $ ( function () {  
 
   ; $ ( "# jQgridPOC" ). jqGrid ({  
 
   ; url: 'http://localhost: 58404/JQGridHandler.ashx ',  
 
   ; datatype: "json" ,  
 
   ; colNames: [ 'Id' , ' name ' , ' surname ' , < span style = "color: # a31515;"> " address " , ' city ' , ' State ' ],  
 
   ; colModel: [  
 
   ; ; {name: 'id' , index: 'id' < / span>, width: 20, stype: 'text' },  
 
   ; ; {name: 'FirstName' , index: 'FirstName' < / span>, width: 80, stype: 'text' , sortable: true , editable: true },  
 
   ; ; {name: 'LastName' , index: 'LastName' < / span>, width: 80, align: "right" , editable: true },  
 
   ; ; {name: 'Address1' , index: 'Address1' < / span>, width: 150, align: "right" , editable: true },  
 
   ; ; {name: 'City' , index: 'City' < / span>, width: 80, align: "right" , editable: true },  
 
   ; ; {name: 'State' , index: 'State' < / span>, width: 100, sortable: false , editable: true }  
 
   ;],  
 
   ; rowNum: 10,  
 
   ; loadonce: true , < / span>  
 
   ; sortname: '_id' ,  
 
   ; viewrecords: true , < / span>  
 
   ; sortorder: 'desc' ,  
 
   ; caption: " customer List " < / span>  
 
    
 
   ;});  
 
   ;});  
 
    
 

</ script >

 

run the program , you will get the form shown below ( currently not data ) .

 

 

I want to display the content according to the table , you should be able to read what I wrote initialization script .

   

 

      
 

     

 

 

 

 

 

       

   

               

   

   

 

 

 

 

 

       

   

 . .

 

 

 

                      

           

 

 

 

           

     

 

 

       

 

 

   

   

   

                
            $('#jQgridPOC').jqGrid('navGrid', '#jQGridPOCPager', 
{
edit:
true,
add:
true,
del:
true,
search:
true,
searchtext:
"查找",
addtext:
"添加",
edittext:
"编辑",
deltext:
"删除",
refreshtext:
"刷新"
},
{
//EDIT EVENTS AND PROPERTIES GOES HERE

},
{
//ADD EVENTS AND PROPERTIES GOES HERE
},
{
//DELETE EVENTS AND PROPERTIES GOES HERE
},
{
//SEARCH EVENTS AND PROPERTIES GOES HERE

}
);
  
   View Code  
   

   

       

     

 

     

       

     

 
       
     

 

 

       

     

 

       

 

       

                
 $(function () { 
$(
"#jQgridPOC").jqGrid({
url:
'http://localhost:58404/JQGridHandler.ashx',
datatype:
"json",
colNames: [
'Id', '大名', '尊姓', "地址", '城市', '州','国家'],
colModel: [
{ name:
'id', index: 'id', width: 20, stype: 'text' },
{ name:
'FirstName', index: 'FirstName', width: 80, stype: 'text', sortable: true, editable: true },
{ name:
'LastName', index: 'LastName', width: 80, align: "right", editable: true },
{ name:
'Address1', index: 'Address1', width: 150, align: "right", editable: true },
{ name:
'City', index: 'City', width: 100, align: "right", editable: true },
{ name:
'State', index: 'State', width: 80, sortable: false, editable: true },
{ name:
'Country', index: 'Country', width: 80, sortable: false, editable: true }
],
rowNum:
10,
loadonce:
true,
rowList: [
10, 20, 30],
pager:
'#jQGridPOCPager',
sortname:
'LastName',
viewrecords:
true,
sortorder:
'desc',
caption:
"客户列表",
editurl:
'http://localhost:58404/JQGridHandler.ashx'
});


$(
'#jQgridPOC').jqGrid('navGrid', '#jQGridPOCPager',
{
edit:
true,
add:
true,
del:
true,
search:
true,
searchtext:
"查找",
addtext:
"添加",
edittext:
"编辑",
deltext:
"删除",
refreshtext:
"刷新"
},
{
//EDIT
// height: 300,
// width: 400,
// top: 50,
// left: 100,
// dataheight: 280,
closeOnEscape: true,//Closes the popup on pressing escape key
reloadAfterSubmit: true,
drag:
true,
afterSubmit:
function (response, postdata) {
if (response.responseText == "") {

$(
this).jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid');//Reloads the grid after edit
return [true, '']
}
else {
$(
this).jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid'); //Reloads the grid after edit
return [false, response.responseText]//Captures and displays the response text on th Edit window
}
},
editData: {
EmpId:
function () {
var sel_id = $('#jQGridDemo').jqGrid('getGridParam', 'selrow');
var value = $('#jQGridDemo').jqGrid('getCell', sel_id, '_id');
return value;
}
}
},
{
closeAfterAdd:
true,//Closes the add window after add
afterSubmit: function (response, postdata) {
if (response.responseText == "") {

$(
this).jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid')//Reloads the grid after Add
return [true, '']
}
else {
$(
this).jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid')//Reloads the grid after Add
return [false, response.responseText]
}
}
},
{
//DELETE
closeOnEscape: true,
closeAfterDelete:
true,
reloadAfterSubmit:
true,
closeOnEscape:
true,
drag:
true,
afterSubmit:
function (response, postdata) {
if (response.responseText == "") {

$(
"#jQGridDemo").trigger("reloadGrid", [{ current: true }]);
return [false, response.responseText]
}
else {
$(
this).jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid')
return [true, response.responseText]
}
},
delData: {
EmpId:
function () {
var sel_id = $('#jQGridDemo').jqGrid('getGridParam', 'selrow');
var value = $('#jQGridDemo').jqGrid('getCell', sel_id, '_id');
return value;
}
}
},
{
//SEARCH
closeOnEscape: true

}
);

});
  
   View Code  
   

   

 

 

 

 

 

   

 

                  
    public class JQGridHandler : IHttpHandler 
{

public
void ProcessRequest(HttpContext context)
{
NameValueCollection forms
= context.Request.Form;
string strOperation
= forms.Get("oper");
string strResponse
= string.Empty;
if (strOperation == null) //oper = null which means its first load.
{
//1.get the sample data
DataTable dt = GetAccountInfo();
//2.convert to json
string jsonRes = GetJson(dt);
context.Response.Write(jsonRes);
}
else if (strOperation == "del")
{
string strEmpId
= forms.Get("id").ToString();
DeleteEmployee(strEmpId);
strResponse
= "删除成功";
context.Response.Write(strResponse);

}
else
{
string strOut
= string.Empty;
AddEdit(forms, out strOut);
context.Response.Write(strOut);
}
}

public bool IsReusable
{
get
{
return false;
}
}

private DataTable GetAccountInfo()
{
DataTable dt
= null;
string cmdText
= @"SELECT [UniqueID] id
,[FirstName]
,[LastName]
,[Address1]
,[City]
,[State]
,[Country]
FROM [MSPetShop4Profile].[dbo].[AccountTest]
";
SQLHelper sqlhelper
= new SQLHelper();
dt
= sqlhelper.ExecuteQuery(cmdText, CommandType.Text);
return dt;
}

//convert a data table to JSON format
public string GetJson(DataTable dt)
{
JavaScriptSerializer serializer
= new JavaScriptSerializer();
List
<Dictionary<string, object>> rows =
new List<Dictionary<string, object>>();
Dictionary
<string, object> row = null;

foreach (DataRow dr
in dt.Rows)
{
row
= new Dictionary<string, object>();
foreach (DataColumn col
in dt.Columns)
{
row.Add(col.ColumnName.Trim(), dr[col]);
}
rows.Add(row);
}
return serializer.Serialize(rows);
}

private
void AddEdit(NameValueCollection forms, out string strResponse)
{
string strOperation
= forms.Get("oper");
string strEmpId
= string.Empty;
string strFirstName
= forms.Get("FirstName").ToString();
string strLastName
= forms.Get("LastName").ToString();
string strAddress
= forms.Get("Address1").ToString();
string strCity
= forms.Get("City").ToString();
string strState
= forms.Get("State").ToString();
string strCountry
= forms.Get("Country").ToString();

Employee objEmp
= new Employee();
objEmp._id
= strEmpId;
objEmp.FirstName
= strFirstName;
objEmp.LastName
= strLastName;
objEmp.Address1
= strAddress;
objEmp.City
= strCity;
objEmp.State
= strState;
objEmp.Country
= strState;
if (strOperation == "add")
{
InsertEmployee(objEmp);
strResponse
= "资料添加成功";
return;

}
else if (strOperation == "edit")
{
strEmpId
= forms.Get("id").ToString();
objEmp._id
= strEmpId;
UpdateEmployee(objEmp);
strResponse
= "资料更新成功";
}

strResponse
= "更新有问题,请联系管理员";
}

//insert
public bool InsertEmployee(Employee employee)
{

bool flag
= false;
SQLHelper sqlhelper
= new SQLHelper();

string cmdText
= @"INSERT INTO [MSPetShop4Profile].[dbo].[AccountTest]
([FirstName]
,[LastName]
,[Address1]
,[City]
,[State]
,[Country])
VALUES
(@FirstName
,@LastName
,@Address1
,@City
,@State
,@Country)
";

SqlParameter[] paras
= new SqlParameter[]{
new SqlParameter("@FirstName",employee.FirstName),
new SqlParameter("@LastName",employee.LastName),
new SqlParameter("@Address1",employee.Address1),
new SqlParameter("@City",employee.City),
new SqlParameter("@State",employee.State),
new SqlParameter("@Country",employee.Country)
};
try
{
int res = sqlhelper.ExecuteNonQuery(cmdText, paras, CommandType.Text);
if (res > 0)
{
flag
= true;
}
}
catch (Exception ex)
{

throw ex;
}

return flag;
}

//update
public bool UpdateEmployee(Employee employee)
{

bool flag
= false;
SQLHelper sqlhelper
= new SQLHelper();

string sql
= @"UPDATE [MSPetShop4Profile].[dbo].[AccountTEST]
SET [FirstName] = @FirstName
,[LastName] = @LastName
,[Address1] = @Address1
,[City] = @City
,[State] = @State
,[Country] = @Country
WHERE UniqueID=@UniqueID
";
SqlParameter[] paras
= new SqlParameter[]{
new SqlParameter("@UniqueID",employee._id),
new SqlParameter("@FirstName",employee.FirstName),
new SqlParameter("@LastName",employee.LastName),
new SqlParameter("@Address1",employee.Address1),
new SqlParameter("@City",employee.City),
new SqlParameter("@State",employee.State),
new SqlParameter("@Country",employee.Country)
};
int res = sqlhelper.ExecuteNonQuery(sql, paras, CommandType.Text);
if (res > 0)
{
flag
= true;
}
return flag;
}

//delete
public bool DeleteEmployee(string id)
{

bool flag
= false;
SQLHelper sqlhelper
= new SQLHelper();

string sql
= @"DELETE FROM [MSPetShop4Profile].[dbo].[AccountTEST]
WHERE UniqueID=@UniqueID
";
SqlParameter[] paras
= new SqlParameter[]{
new SqlParameter("@UniqueID",id)
};
int res = sqlhelper.ExecuteNonQuery(sql, paras, CommandType.Text);
if (res > 0)
{
flag
= true;
}
return flag;
}
}
  
   View Code  
 

              

   

   

      
 
 

没有评论:

发表评论