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.

650) this. width = 650; "alt =" "src =" http://www.bkjia.com/uploads/allimg/131228/1243034J9-0.PNG "/>

Figure 21 user management view with no layout configured

The toolbar at the bottom is under the title bar of the 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.

650) this. width = 650; "alt =" "src =" http://www.bkjia.com/uploads/allimg/131228/1243032012-1.PNG "/>

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"

650) this. width = 650; "alt =" "src =" http://www.bkjia.com/uploads/allimg/131228/1243031155-2.PNG "/> figure 23 view the position of the 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.

650) this. width = 650; "alt =" "src =" http://www.bkjia.com/uploads/allimg/131228/1243035649-3.PNG "/>

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 to use the GetRolesForUser method to return a String Array Based on the role returned by the user name, and then convert it to a JSON array directly 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.

650) this. width = 650; "alt =" "src =" http://www.bkjia.com/uploads/allimg/131228/124303K40-4.PNG "/>

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.

650) this. width = 650; "alt =" "src =" http://www.bkjia.com/uploads/allimg/131228/1243032461-5.PNG "/>

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

This article from the "yellow light bridge blog", please be sure to keep this source http://dqhuang.blog.51cto.com/2522725/1007495

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.