Step by step use ext js mvc and ASP. Net MVC 3 to develop a simple CMS background management system for user management (2)

Source: Internet
Author: User

Now, create a view. Create the users directory under the scripts \ app \ view directory, and then create view. js under the directory. To use a grid to display user information, you must derive a view from the grid panel. Pay attention to the Class Name of the view during definition. In addition, you must define the alias, because in the controller, the view instance is created using the widget method. If you do not want to define an alias, you must modify the instance creation method. The specific basic definition code is as follows:

Ext. Define ('simplecms. View. Users. view ',{

Extend: 'ext. Grid. Panel ',

Alias: 'widget. usersview ',

Title: "User Management ",

ID: "usersview ",

 

Initcomponent: function (){

VaR me = this;

 

Me. callparent (arguments );

}

 

});

 

 

The ID in the code can be defined as needed. Here, no matter whether it is used or not, it should be defined first. If there are too many project classes, avoid ID conflicts. The title definition is optional, because it is in the tab and you need it.

Grid requires a store. Therefore, the store configuration item is added first, and the store is users. Therefore, the definition code is as follows:

Store: "users ",

 

The column definition can be directly defined using the configuration item, or defined in the initcomponent method. For details, see the situation. For example, to add an editing component for the column, therefore, the definition in the initcomponent method is more appropriate. The Code is as follows:

Me. Columns = [

{Text: 'username', dataindex: 'username', flex: 1 },

{Text: 'email ', dataindex: 'email', flex: 1 },

{Text: 'role', dataindex: 'roles ', flex: 1 },

{Xtype: "datecolumn", text: 'creation time', dataindex: 'created ', format: "Y-m-d h: I: s", width: 150 },

{Xtype: "datecolumn", text: 'Last logon time', dataindex: 'created ', format: "Y-m-d h: I: s", width: 150 },

{Xtype: 'checkcolumn', dataindex: "isapproved", text: "Allow Logon", winth: 150}

]

 

 

Currently, some basic code has been defined and no editing component has been defined. In this way, debugging the display and entering the next stage can reduce errors. In the last field, the extended checkcolumn is used. Therefore, you need to copy the checkcolumn. js file to the ext \ UX directory in the ext package and add the requires configuration item. The Code is as follows:

Requires: ["Ext. UX. checkcolumn"],

 

Add a paging toolbar in the top toolbar. The Code is as follows:

Me. tbar = {

Xtype: "pagingtoolbar ",

Pagesize: 50, displayinfo: True, store: Me. Store

}

 

The number of records displayed on each page is set to 50, which can be adjusted as needed.

Finally, add a text description on the toolbar at the bottom. The Code is as follows:

Me. bbar = ["double-click a user to enter the editing status. The user password is" 123456 "by default ". Reset the password to 123456 ". "]

 

Now, the prototype of the view has been developed. You can debug the result. Open the page in the browser and log on with Admin. Switch to the user management tab to see the effect shown in Figure 21.

Figure 21 user management view with no layout configured

Is it strange that the toolbar at the bottom is under the title bar of grid. For the author, we can see that the layout is not set, and the height of the grid subject is 0. For new users, it is not difficult to debug the problem. In particular, if the illuminations plug-in is available, switch the panel to the illuminations panel in firebug, click the button, and then click the title bar of the view, the result shown in firebug 22 is displayed.

Figure 22 locate an object on the illuminations panel

In the path on the right of the element, click the view in the yellow highlighted part of the graph, and move the mouse over the view object as 23. The view part is circled with a red border, this indicates that the view does not fill the entire tab body, indicating that the tab layout is faulty. Switch to the main panel view (mainpanel. JS) in Vs and add the following code to add the user management panel:

Layout: "fit"

Figure 23 view the position of a view

After the fit layout is used, the view can fill the tab panel subject. Now, refresh the page and switch to the user management tab to see the correct effect shown in 24.

 

Figure 24 correct view display

Now, create a users controller on the server side to provide data for the grid. Create a controller named userscontroller In the controllers directory. After adding necessary references, modify the index method to the list method and return the result as jobject. The Code is as follows:

Publicjobject list ()

{

}

 

The getallusers of the membership provider can be used for paging. The only problem is that the sorting cannot be performed and will not be processed here. Another note is that the returned role must be in the array format. Otherwise, a problem may occur when setting the value for ComboBox.

The structure of the data to be returned is as follows:

{

Success: true or false,

Total: Total number of records,

MSG: error message,

Data: An array composed of records on the current page

}

 

In the structure, success indicates whether the returned results are successful. If it fails, you can use MSG to obtain the error message. If it succeeds, it reads data from the data. The total in the structure is very important. The client will calculate the number of pages based on this value, so it must be returned correctly, otherwise the page will be messy.

To adapt the writejobjectresult method created in the myfunction class to this structure, you must add parameters. However, it is also a good choice to overload this method. The Code is as follows:

Publicstatic jobject writejobjectresult (bool success, int total, string message, jarray data)

{

Return new jobject {

Newjproperty ("success", success ),

New jproperty ("Total", total ),

New jproperty ("MSG", message ),

New jproperty ("data", data)

};

}

 

Now you can complete the code for the list method. The Code is as follows:

Publicjobject list ()

{

Try

{

Int pagesize = 50;

Int page = 0;

Int. tryparse (request ["page"], out page );

If (page <= 0) page = 1;

Int Total = 0;

Jarray ja = new jarray ();

Foreach (membershipuser C inmembership. getallusers (page-1, pagesize, out total ))

{

String [] rolesforuser = roles. getrolesforuser (C. username );

Ja. Add (New jobject {

Newjproperty ("ID", C. provideruserkey ),

Newjproperty ("username", C. username ),

Newjproperty ("email", C. Email ),

Newjproperty ("isapproved", C. isapproved ),

Newjproperty ("lastlogindate", C. lastlogindate. tostring ("yyyy-mm-DDHH: mm: SS ")),

Newjproperty ("created", C. creationdate. tostring ("yyyy-mm-DDHH: mm: SS ")),

Newjproperty ("Roles", new jarray (rolesforuser. Select (M => m )))

});

}

Returnmyfunction. writejobjectresult (true, total, "", ja );

}

Catch (exception E)

{

Returnmyfunction. writejobjectresult (false, 0, E. Message, null );

}

}

 

In the above Code, the first thing to note is that in the getallusers method, the page is counted as the first page from 0. The second thing to note is that the role returned by the user name is a String Array Using the getrolesforuser method, and then it can be directly converted to a JSON array through LINQ. Other code is not too difficult. If you do not understand it, you can directly send an email or leave a message to me.

To prevent unexpected situations, the try module is added here. When an error occurs, the error message is returned as the value of the MSG keyword. Whether to directly return the error message in this way depends on the project or your preferences.

In the client script, There is no code to process the error message. Therefore, the error message returned here is invisible to the client. To handle such an error message, you must listen to the exception event in the store proxy. Because the callback functions of the exception event are the same, they can be processed in a single function, and no replication is required.

Switch to index. cshtml and add the following code under Ext. ns to define the callback for handling exception events:

Simplecms. proxyexception = function (proxy, response, opts ){

Ext. msg. Alert ("error message", opts. Error );

}

 

The third parameter returned by the callback function of the exception event is the operation object. when success is false, it copies the value of the MSG keyword to the error attribute of the object, therefore, you can directly call this attribute to obtain the error message. There are still many exceptions to be handled here, such as the server's failure to return data and response latency. We will not list them here. You can complete this function according to the API instructions.

Next, switch to the users store and add the listeners configuration item in the proxy definition to listen to the exception event. The Code is as follows:

Listeners :{

Exception: simplecms. proxyexception

}

 

Someone may ask, why not write the listening code for the proxy in the controller? This ...... I really don't know how to answer this question. It's still the old rule. I believe that it is necessary to Plug everything into the controller. Is the code really easy to maintain? If this problem arises, it is estimated that it is a battle. Choose it based on your preferences!

To test whether the exception event can be executed properly, add the following code before the code defined in pagesize to throw an exception:

Throw new exception ("error occurred. ");

 

Regenerate the solution, refresh the page, and switch to user management. The error message 25 is displayed, indicating that the listening code works properly.

Figure 25 error message displayed for the exception event

Delete the thrown Exception Code and compile it again. Close the dialog box in the browser and click the refresh button on the toolbar to view the data shown in Figure 26.

 

The user data list has been completed, and the rest is to add, edit, delete, and reset the password.

Source code download: http://download.csdn.net/detail/tianxiaode/4600348

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.