Step by step use ExtJSMVC and Asp. NetMVC3 to develop a simple CMS background management system user management (4)

Source: Internet
Author: User
Now you can complete the deletion function. Currently, only one row can be selected for a Grid, that is, only one row can be deleted at a time, which is not convenient. Therefore, you need to set it to use the check box and allow multiple selections. In the User View Script file, add the following configuration items to implement this: selType: & quot; checkbo... SyntaxHighlighter. all ();

Now you can complete the deletion function. Currently, only one row can be selected for a Grid, that is, only one row can be deleted at a time, which is not convenient. Therefore, you need to set it to use the check box and allow multiple selections. In the User View Script file, add the following configuration items to achieve this:
SelType: "checkboxmodel ",
SelModel: {checkOnly: false, mode: "MULTI "},
 
Open the page and you will see the effect shown in Figure 29. You can select the row through the check box on the far left.

9. check box is added to select the Grid of the row
There are two ways to delete users. One is to use the remove Method to delete records in the Store, and then call the sync method for synchronization. The other is to extract the id of the selected row, then, submit it to the server in Ajax mode for deletion. After confirmation, refresh the page on the client. The first method must define the destroy configuration item in the proxy api definition, which has been defined in the previous Code. Therefore, this method is used in this example. If the destroy configuration item is also defined in the second method, do not use remove to delete the Store record. Otherwise, when adding or editing, when you call the sync method for synchronization, the deleted data will be submitted together. Select that method! Haha.
Now switch to the Users controller script and bind the click event to the delete button. The Code is as follows:
Me. getButtonUserDelete (). on ("click", me. onDeleteUser, me );
 
In the onDeleteUser method, you must first obtain the selected records from the Store selection model. If you have selected a record, the system first prompts you whether to delete the user. After confirmation, call the remove Method to delete the record and call the sync method to synchronize data. If successful, call the commitChanges method to confirm the modification. Otherwise, call the rejectChanges method to cancel the modification. The Code is as follows:
OnDeleteUser: function (){
Var me = this,
Sm = me. getUserView (). getSelectionModel ();
If (sm. getCount ()> 0 ){
Var rs = sm. getSelection ();
Content = ["are you sure you want to delete the following users? "];
For (var I = 0; ln = rs. length, I <ln; I ++ ){
Content. push (rs [I]. data. Username );
}
Ext. Msg. confirm ("delete user", content. join ("
"), Function (btn ){
If (btn = "yes "){
Varme = this,
Rs = me. getUserView (). getSelectionModel (). getSelection ()
Store = me. getUsersStore ();
Store. remove (rs );
Store. sync ({
Success: function (e, opt ){
Var me = this;
Me. getUsersStore (). commitChanges ();
},
Failure: function (e, opt ){
Var me = this;
Me. getUsersStore (). rejectChanges ()
Ext. Msg. alert ("error occurred", e. exceptions [0]. error );
},
Scope: me
});
}
}, Me)
} Else {
Ext. Msg. alert ('delete user', 'select the user to delete. ');
}
}
 
In the code, array content is used to combine validation information. After the user confirms, the remove method is called and the sync method is called.
The server code is now completed. Because the sync method submits data in a fixed way, the method for extracting and deleting data is the same as that for adding and Editing data. You need to extract data from the data and then convert it to JArray using the parse method. The remaining work is to extract the JObject for data deletion from JArray and delete the user through id or Username. The specific code is as follows:
Public JObject Delete ()
{
String msg = "";
Bool success = false;
JArray ja = null;
String data = Request ["data"]? "";
If (string. IsNullOrEmpty (data ))
{
Msg = "incorrect data submission. ";
}
Try
{
Ja = JArray. Parse (data );
If (ja. Count> 0)
{
Foreach (JObject jo in ja)
{
Membership. DeleteUser (string) jo ["Username"]);
}
Success = true;
}
Else
{
Msg = "incorrect data submission. ";
}
}
Catch (Exception e)
{
Msg = e. Message;
}
Return MyFunction. WriteJObjectResult (success, 0, msg, ja );
}
 
 
It should be noted that, like adding and editing operations, the deleted data should be returned even if success returns true. Because the deletion does not need to change the original data, the ja is returned directly.
There are two more questions to consider. The first one is whether the user is prompted to delete the record after deletion. If necessary, add the prompt information to the callback function success in the sync method. The 2nd problem is that after data is deleted, the data in the Grid decreases. Do you need to refresh the page?
The last function Reset Password is similar to deleting a user. It also gets the SELECTION record from the selection model. However, this time, you cannot use sync synchronization. You can only extract the id and then use Ajax to submit data. First, bind the click event for the Reset Password button. The Code is as follows:
Me. getButtonUserResetPassword (). on ("click", me. onResetPassword, me );
Then complete the onResetPassword method. The Code is as follows:
OnResetPassword: function (){
Var me = this,
Rs = me. getUserView (). getSelectionModel (). getSelection ();
If (rs. length> 0 ){
Var idList = [];
For (var I = rs. length-1; I> = 0; I --){
IdList. push (rs [I]. data. id );
}
Ext. Ajax. request ({
Params: {id: idList },
Url: '/Users/resetpassword ',
Scripts: true,
Scope: me,
Success: function (response, opt ){
Varobj = Ext. JSON. decode (response. responseText );
If (obj ){
If (obj. success ){
Ext. Msg. alert ("prompt message", "Password Reset successful ");
Return;
} Else {
Ext. Msg. alert ("error", obj. Msg );
}
}
},
Failure: function (response, options ){
Ext. Msg. alert ("error", "failed to Reset Password!
Error message: "+ response. responseText );
}
});
}
}
 
The code is not confirmed. If necessary, you can add it on your own. Because Ajax submission does not call the success method or failure method based on the returned success value, as long as it is not a page error, the success method of the callback function will be executed. Therefore, you must perform the following based on the returned data, call the decode method to convert the data to an object and handle the data according to the success value.
Next, complete the ResetPassword method on the server side. Here, there is a problem: the ChangePassword method needs to use the old password to change to a new one, and the ResetPassword method will generate a random password, and cannot directly set the password to 123456. Therefore, use the ResetPassword method to reset the password, and then use the Reset Password to call the ChangePassword method to change the password to 123456. The specific code is as follows:
Public JObject ResetPassword ()
{
Bool success = false;
String msg = "";
String idList = Request ["id"]? "";
Try
{
String [] ids = idList. Split (new char [] {','}, StringSplitOptions. RemoveEmptyEntries );
Foreach (var c in ids)
{
Guid id = Guid. Parse (c );
MembershipUser user = Membership. GetUser (id );
If (user! = Null)
{
String pwd = user. ResetPassword ();
User. ChangePassword (pwd, "123456 ");
}
}
Success = true;
}
Catch (Exception e)
{
Msg = e. Message;
}
Return MyFunction. WriteJObjectResult (success, 0, msg, null );
 
}
 
 
The basic functions of user management have all been completed, but there is another problem to be solved, that is, to control the permissions of the server-side user controller. This is easily implemented in Asp. Net MVC and can be solved by using the Authorize feature declaration method. The Code is as follows:
[Authorize (Roles = "System Administrator")]
No, there is a problem here. The returned error message is not in JSON format, so there will be problems in the client processing. Therefore, you need to customize an authentication feature that returns the JSON format. To achieve this, it is not difficult to derive an AjaxAuthorizeAttribute class from AuthorizeAttribute and rewrite the HandleUnauthorizedRequest method.
Add a directory named Validations under the solution. Add a class file named AjaxAuthorizeAttribute. cs under the directory. The generated code is as follows:
UsingSystem;
UsingSystem. Collections. Generic;
UsingSystem. Linq;
UsingSystem. Web;
 
Namespace SimpleCMS. Validations
{
Public class AjaxAuthorizeAttribute
{
}
}
 
First, modify the class structure so that the AjaxAuthorizeAttribute class is derived from AuthorizeAttribute. The modified code is as follows:
Public classAjaxAuthorizeAttribute: AuthorizeAttribute
{
}
 
In this case, you will be prompted to add the following references:
UsingSystem. Web. Mvc;
 
Now, add the code to override the HandleUnauthorizedRequest method in the class. The Code is as follows:
Protected override voidHandleUnauthorizedRequest (AuthorizationContext filterContext)
{
}
 
The parameter passed in is the context for verification. Determine the IsAjaxRequest method of the Request object in the context to know whether to submit the Ajax Request. If yes, construct a JSON result and return it. The Code is as follows:
If (filterContext. HttpContext. Request. IsAjaxRequest ())
{
 
UrlHelperurlHelper = new UrlHelper (filterContext. RequestContext );
FilterContext. Result = new JsonResult
{
Data = new
{
Success = false,
Msg = "You are not authorized to access this page. "
},
JsonRequestBehavior = JsonRequestBehavior. AllowGet
};
}
Else
{
Base. HandleUnauthorizedRequest (filterContext );
}
 
All right, add a reference to Validations in the controller, and add the following features to all methods:
[AjaxAuthorize (Roles = "System Administrator")]
 
In this way, you can control the access permission. to test whether the access is successful, you can copy the Ajax request for Password Reset to the Firebug command line, change idList to 1, and delete "scope: me ". Before running, check whether the system has been exited to ensure that the system is not logged on. After you click Run, you will see the result shown in 30. In Firebug, you will see the returned result, which is exactly the returned result defined in the AjaxAuthorizeAttribute class.

0 test Permissions
Now, the user management function is complete.

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.