ExtJs GridPanel simple addition, deletion, and modification implementation code

Source: Internet
Author: User

1. First, let's take a look:

2. ext code
Copy codeThe Code is as follows:
// <Reference path = "http://www.cnblogs.com/Resources/ExtJs/vswd-ext_2.0.2.js"/>
Ext. namespace ('xqh. ExtJs. framework ');
XQH. ExtJs. Frame. RoleManage = function (){
This. init ();
};
Ext. extend (XQH. ExtJs. Frame. RoleManage, Ext. util. Observable ,{
Init: function (){
// Form
AddForm = new Ext. form. FormPanel ({
Id: 'addroleform ',
Width: 460,
Height: 250,
// Style
BodyStyle: 'margin: 5px 5px 5px 5px ',
Frame: true,
Xtype: 'ledset ',
LabelWidth: 60,
Items:
[
{
Xtype: 'fieldset ',
Title: 'Role information ',
Collapsible: true,
AutoHeight: true,
AutoWidth: true,
Items:
[
{
Xtype: 'textfield ',
Name: 'rolename ',
FieldLabel: 'Role name ',
EmptyText: 'required ',
BlankText: 'Role name cannot be blank ',
AllowBlank: false,
MaxLength: 10,
MaxLengthText: 'The role cannot exceed 10 characters ',
Anchor: '000000'
}
]
},
{
Xtype: 'fieldset ',
Title: 'Role description ',
Collapsible: true,
AutoHeight: true,
AutoWidth: true,
Items:
[
{Html: 'This is the description ...'}
]
}
],
Reader: new Ext. data. JsonReader ({
Root: 'data ',
Fields :[
{Name: 'roleid', mapping: 'roleid', type: 'int '},
{Name: 'rolename', mapping: 'rolename', type: 'string '}
]
})
});
// New user window
AddWin = new Ext. Window ({
Id: 'addrolewin ',
Title: 'Add a role ',
Width: 480,
Height: 210,
// Background mask
Modal: true,
// Reset the size
Resizable: false,
// Action executed when the close button is clicked
CloseAction: 'hide ',
Plain: true,
ButtonAlign: 'center ',
Items: addForm,
Buttons:
[
{Text: 'close', handler: function () {Ext. getCmp ('addrolewin'). hide ();}},
{Text: 'Submit', id: 'btnsubmit '}
]
});
// Add a role event
Function addRoleFunction (){
Var submitButton = this;
SubmitButton. disable ();
Var userForm = Ext. getCmp ("addRoleForm ");
If (userForm. form. isValid ()){
UserForm. form. doAction ('submit ',{
Url: "http://www.cnblogs.com/Service/SystemService/RoleService.ashx? Method = AddRole ",
Method: 'post ',
WaitTitle: "Please wait ",
WaitMsg: 'adding data ...',
Success: function (form, action ){
SubmitButton. enable ();
Ext. getCmp ('rollgd '). store. reload ();
UserForm. ownerCt. hide ();
},
Failure: function (form, action ){
Var tip = "failed to add! ";
If (action. result. rspText! = "")
Tip = action. result. rspText;
Ext. Msg. alert ('hprompt ', tip );
SubmitButton. enable ();
}
});
}
Else {
SubmitButton. enable ();
}
};
// Add button click event
Function btnAddClick (){
Ext. getCmp ('addroleform'). form. reset ();
Ext. getCmp ("addRoleWin"). setTitle ('add role ');
Ext. getCmp ("addRoleWin"). buttons [1]. handler = addRoleFunction;
Ext. getCmp ("addRoleWin"). show ();
};
// Modify a role event
Function updateRoleFunction (){
Var submitButton = this;
SubmitButton. disable ();
Var userForm = Ext. getCmp ("addRoleForm ");
Var id = userForm. form. reader. jsonData. data [0]. RoleId;
If (userForm. form. isValid ()){
UserForm. form. doAction ('submit ',{
Url: 'http: // www.cnblogs.com/Service/SystemService/RoleService.ashx? Method = UpdateRoleById & RoleId = '+ id,
Method: 'post ',
// Params :{},
WaitTitle: "Please wait ",
WaitMsg: 'saving data ...',
Success: function (form, action ){
SubmitButton. enable ();
Ext. getCmp ('rollgd '). store. reload ();
UserForm. ownerCt. hide ();
},
Failure: function (form, action ){
Var tip = "failed to save the editing activity! ";
If (action. result. text! = "" & Action. result. text! = Null)
Tip = action. result. text;
Ext. Msg. alert ('hprompt ', tip );
SubmitButton. enable ();
}
});
}
Else {
SubmitButton. enable ();
}
};
// Click the event button
Function btnUpdateClick (){
Var grid = Ext. getCmp ('rolegd ');
If (grid. getSelectionModel (). getSelections () [0] = undefined ){
Ext. Msg. alert ("prompt", "select the row to be modified ");
}
Else {
Ext. getCmp ('addrolewin'). setTitle ('modify roame ');
Ext. getCmp ("btnSubmit"). handler = updateRoleFunction;
Ext. getCmp ("addRoleForm"). form. reset ();
Var roleId = grid. getSelectionModel (). getSelections () [0]. data. RoleId;
Var url = 'HTTP: // www.cnblogs.com/Service/SystemService/RoleService.ashx? Method = GetRoleById & roleId = '+ roleId;
Ext. getCmp ("addRoleWin"). show ();
Ext. getCmp ("addRoleForm"). load ({
Url: url,
WaitTitle: "Please wait ",
WaitMsg: 'loading data ...',
Success: function (form, action ){
},
Failure: function (form, action ){
Var tip = "failed to submit ";
If (action. response. responseText! = "")
Tip = action. response. responseText;
Ext. Msg. alert ('hprompt ', tip );
}
});
}
};
// Delete a role function
Function delRoleFunction (){
Var grid = Ext. getCmp ('rolegd ');
If (grid. getSelectionModel (). getSelections () [0] = undefined ){
Ext. Msg. alert ("prompt", "select the role to delete ");
}
Else {
Ext. MessageBox. confirm ('hprompt ',' Are you sure you want to delete the selected role? ', Function (btn ){
If (btn = 'yes '){
Var conn = new Ext. data. Connection ();
Conn. request
({
Url: 'http: // www.cnblogs.com/Service/SystemService/RoleService.ashx? Method = DeleteRoleById ',
Params: {Id: grid. getSelectionModel (). getSelections () [0]. data. RoleId },
Method: 'post ',
Scope: this,
Callback: function (options, success, response ){
If (success ){
Ext. getCmp ('rollgd '). store. reload ();
}
Else {
Ext. MessageBox. alert ("prompt", "deletion failed! ");
}
}
});
}
});
}
};
// Toolbar
ToolBar = new Ext. Toolbar ({
Items:
[
{Text: 'add', id: 'btnadd '},
'-',
{Text: 'modify', id: 'btnupdate '},
'-',
{Text: 'delete', handler: delRoleFunction}
]
});
// Add button
Var addUserBtn = Ext. getCmp ('btnadd ');
AddUserBtn. on ('click', btnAddClick );
// Modify button
Var btnUpdate = Ext. getCmp ('btnupdate ');
BtnUpdate. on ('click', btnUpdateClick );
Var dataStore = new Ext. data. Store ({
Proxy: new Ext. data. HttpProxy ({
Url: 'http: // www.cnblogs.com/Service/SystemService/RoleService.ashx? Method = GetAllRoles'
}),
Reader: new Ext. data. JsonReader ({
Root: 'table ',
TotalProperty: 'recordcount ',
Id: 'roleid ',
Fields: ['roleid', 'rolename']
})
});
DataStore. load ({params: {start: 0, limit: 20 }});
// Grid
Var roleGrid = new Ext. grid. GridPanel ({
Region: 'center ',
Id: 'rolegd ',
Title: 'Role management ',
Store: dataStore,
Columns:
[
New Ext. grid. RowNumberer ({header: "No.", width: 50 }),
{Header: "RoleId", width: 50, sortable: false, dataIndex: 'roleid', hidden: true },
{Header: "role name", width: 50, sortable: true, dataIndex: 'rolename '}
],
LoadMask: {msg: "loading ..."},
StripeRows: true,
ViewConfig :{
ForceFit: true
},
Sm: new Ext. grid. RowSelectionModel ({singleSelect: true }),
Bbar: new Ext. PagingToolbar ({
PageSize: 20,
Store: dataStore,
DisplayInfo: true,
DisplayMsg: "displays records from {0} to {1}, total records from {2 ",
EmptyMsg: "No record"
}),
Tbar: toolBar
});
// Layout
Var roleView = new Ext. Panel ({
RenderTo: 'rolemain ',
Height: 550,
Layout: 'border ',
Border: false,
Items: [roleGrid]
});
},
Destroy: function (){
}
});

3. linq code
Copy codeThe Code is as follows:
Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;
Namespace XQH. ExtJs. LinqDatabase
{
Public class RoleLinqAccess
{
LinqDatabaseDataContext db = new LinqDatabaseDataContext ();
/// <Summary>
/// Obtain all roles
/// </Summary>
/// <Param name = "start"> </param>
/// <Param name = "limit"> </param>
/// <Param name = "total"> </param>
/// <Returns> </returns>
Public List <XRole> GetAllRole (int start, int limit, out int total)
{
Var q = from r in db. XRole
Select r;
Total = q. Count ();
If (limit = 0)
{
Return q. ToList ();
}
Else
{
Return q. Skip (start). Take (limit). ToList ();
}
}
/// <Summary>
/// Obtain the role by ID
/// </Summary>
/// <Param name = "id"> </param>
/// <Returns> </returns>
Public XRole GetRoleById (int id)
{
Var q = from r in db. XRole
Where r. RoleId = id
Select r;
Return q. First ();
}
/// <Summary>
/// Add a role
/// </Summary>
/// <Param name = "role"> </param>
/// <Returns> </returns>
Public List <XRole> AddRole (XRole role)
{
Db. XRole. InsertOnSubmit (role );
Db. SubmitChanges ();
Return db. XRole. ToList ();
}
/// <Summary>
/// Delete a role by ID
/// </Summary>
/// <Param name = "id"> </param>
/// <Returns> </returns>
Public List <XRole> DelRoleById (int id)
{
Var q = from r in db. XRole
Where r. RoleId = id
Select r;
Db. XRole. DeleteAllOnSubmit (q );
Db. SubmitChanges ();
Return db. XRole. ToList ();
}
/// <Summary>
/// Update a role
/// </Summary>
/// <Param name = "role"> </param>
/// <Returns> </returns>
Public List <XRole> UpdateRole (XRole role)
{
Var q = from r in db. XRole
Where r. RoleId = role. RoleId
Select r;
Foreach (XRole r in q)
{
R. RoleId = role. RoleId;
R. RoleName = role. RoleName;
}
Db. SubmitChanges ();
Return db. XRole. ToList ();
}
}
}

4. ashx code
Copy codeThe Code is as follows:
/// <Summary>
/// Obtain all roles
/// </Summary>
Public void GetAllRoles ()
{
StringBuilder jsonData = new StringBuilder ();
Int start = Convert. ToInt32 (Request ["start"]);
Int limit = Convert. ToInt32 (Request ["limit"]);
Int total = 0;
List <XRole> lsRole = roleAccess. GetAllRole (start, limit, out total );
JsonConvert <XRole> json = new JsonConvert <XRole> ();
JsonData = json. ToGridPanel (lsRole, total );
Response. Write (jsonData );
Response. End ();
}
/// <Summary>
/// Obtain the role by ID
/// </Summary>
/// <Param name = "id"> </param>
/// <Returns> </returns>
Public void GetRoleById ()
{
StringBuilder jsonData = new StringBuilder ();
Bool success = false;
String rspText = string. Empty;
String id = Request ["RoleId"]. ToString ();
Try
{
XRole role = roleAccess. GetRoleById (Convert. ToInt32 (id ));
Success = true;
RspText = "success ";
JsonConvert <XRole> json = new JsonConvert <XRole> ();
JsonData = json. ToFormPanel (success, rspText, role );
}
Catch (Exception ex)
{
Success = false;
RspText = ex. Message;
}
Response. Write (jsonData );
Response. End ();
}
/// <Summary>
/// Add a role
/// </Summary>
Public void AddRole ()
{
String jsonStr = string. Empty;
Bool success = false;
String rspText = string. Empty;
String roleName = Request ["RoleName"]. ToString ();
XRole role = new XRole ();
Role. RoleName = roleName;
Try
{
RoleAccess. AddRole (role );
Success = true;
RspText = "added successfully! ";
}
Catch (Exception ex)
{
Success = false;
RspText = ex. Message;
}
JsonStr = "{success:" + success. ToString (). ToLower () + ", message: '" + rspText + "! '}";
Response. Write (jsonStr );
Response. End ();
}
/// <Summary>
/// Modify the role according to the role ID
/// </Summary>
Public void UpdateRoleById ()
{
String jsonStr = string. Empty;
Bool success = false;
String rspText = string. Empty;
String RoleId = Request ["RoleId"]. ToString ();
String RoleName = Request ["RoleName"]. ToString ();
XRole role = new XRole ();
Role. RoleId = Convert. ToInt32 (RoleId );
Role. RoleName = RoleName;
Try
{
RoleAccess. UpdateRole (role );
Success = true;
RspText = "modified successfully! ";
}
Catch (Exception ex)
{
Success = false;
RspText = ex. Message;
}
JsonStr = "{success:" + success. ToString (). ToLower () + ", message: '" + rspText + "! '}";
Response. Write (jsonStr );
Response. End ();
}
/// <Summary>
/// Delete a user by ID
/// </Summary>
Public void DeleteRoleById ()
{
String jsonStr = string. Empty;
Bool success = false;
String rspText = string. Empty;
Try
{
Int id = Convert. ToInt32 (Request ["Id"]. ToString ());
List <XRole> lsRole = roleAccess. DelRoleById (id );
Success = true;
RspText = "success ";
}
Catch (Exception ex)
{
Success = true;
RspText = ex. Message;
}
JsonStr = "{success:" + success. ToString (). ToLower () + ", message: '" + rspText + "! '}";
Response. Write (jsonStr );
Response. End ();
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.