Step by step using ext JS mvc with asp.net MVC 3 to develop a simple CMS admin system Login window

Source: Internet
Author: User
Tags pack

After the configuration is complete, the login page will be completed. Because you have to write authentication information to a cookie after logging in, you must make a jump. Of course, do not jump, or do not write authentication information can also be, but the problem is more complex, here or do simple processing more appropriate. Also, the purpose of writing authentication information is to control the permissions of the method in the controller through the attribute.

Since to jump once, there are two kinds of ideas, one is to quickly display the login page, you can not load ext JS, but the use of traditional pages, display a login page, so that the page load fast, users feel better many. The second way is to use the Ext JS window to do a login window, but to load Ext JS library, show a long time, experience is not too good. However, after you have loaded ext JS, you can use the cached data when displaying the main frames page. Use that approach, depending on your preferences or project requirements. This article is a demo of Ext JS, and will use the second way, write a login window.

The login window, as a common component, is also used in other projects, so it is a good fit to write an extension. There is also the question of whether to write an extension of a single pattern or simply an extension. The advantage of a single example pattern is that the Show method is displayed directly on the page, and the benefit of a pure extension is that you can customize the title, icon, and so on by configuring items. The author prefers a single case pattern because it is easier to define these things directly in the extension than to use a configuration item, which is, after all, an extension of JavaScript writing, which can be modified much more easily than using C # language extensions.

With a clear target, you can do it, select the Scripts\extjs\ux directory in Solution Explorer, right-click to select Add, create new item, select JScript file in pop-up window as shown in Figure 6, and modify the name to Login.js (a later item can copy the file directly to the directory) and click the Add button to create the file. Notice here that the filename cannot be named with the full name of the class, because dynamic loading automatically finds the directory and loads the file according to the class name, and the name after the last decimal point in the class name is the filename, for example, the class of the login window is all called Ext.ux.Login, and login is the filename.


If you want to use the EXTJS hint in your script, copy the Ext.js file from the resource bundle that came with the book to the ExtJS directory, and after replication, the following code is generated when you drag ext.js to the Login.js file in Solution Explorer:

<reference path= ". /ext.js "/>

In this way, you can use the instructions in the script Ext js, enter "EXT.CR" in the file, you will see the effect shown in Figure 7.


Now, write the definition of the class, including the parent class, the single example mode, the window title, the width, and the height. The title of the window is "simple CMS background admin system background Login window". The width and height are tentatively 400, then adjust again. The final code is as follows:

Ext.define ("Ext.ux.Login", {
    Extend: "Ext.window.Window",
    Singleton:true,
    title: ' Simple CMS backend admin system background Login window ' ,
    width:400,
    height:400
});

Next, consider the window should contain those configuration items, the window should be modal, can not be closed, can not be resized, closed mode is hidden, hidden mode is offset, and so add the following code:

    Modal:true,
    Closable:false,
    resizable:false,
    closeaction: ' Hide ',
    hidemode: ' Offsets ',



OK, now you want to define the control for the login in the InitComponent method of the window. The General Login window contains a user name, password, and authentication code 3 text entry boxes, as well as a picture, login, and reset button that displays the verification code. The ExtJS controls you need to use include the table single-sided boards, pictures, toolbars, buttons, and text fields. The next thing to do is to first define the form and add the following code to the extension:

    Initcomponent:function () {
        var me = this;
        Me.form = Ext.create (Ext.form.Panel, {
            
        });
	Me.callparent (arguments);
    }

In the code, the Me role is to save the this object in the external scope as a local variable, and the benefits include, first, that if this is a global variable such as window, you can change the global variable to a local variable, improve access efficiency, and allow the closure to access the object. This writing in the Ext JS file throughout the whole, in the spirit of copycat, good things should learn.

Note the name of the object in the Create method, the author does not use a string, so you can directly use the object, and do not need to convert the table to find objects, you can improve speed, I suggest this write.

Call the Callparent method is necessary, otherwise the component runs a problem, can not achieve the expected effect, please refer to the author's book. Next is to define the configuration items of the form, the author is accustomed to the following configuration items:

Border:false, 
bodypadding:5,
bodystyle: "Background: #DFE9F6",

In the code, the first sentence means no borders, and if you like a form with a border, you can remove it or modify it to true. The second sentence means that the form panel is compressed inward 5 pixels so that the components within the form are not glued together with the inner border of the window, which can be set according to your personal preferences.      The third sentence of the role is to make the table side of the background color and window integration, rather than the default white, which is a matter of preference. Then add the table-side Board of the submission address, which is set as Account/login, is the account controller Login method, the code is as follows:

URL: "Account/login",

Because the form is used in a text field, it can be unified to do some definitions, such as the label width of 80, the label separator is a Chinese colon, anchoring is 0, are not allowed to empty, the code is as follows:

DefaultType: "TextField",
fielddefaults: {
    labelwidth:80, 
labelseparator: ":", 
Anchor: "0", 
Allowblank:false
},

The next step is to define the field, which is simple, because the default settings already have several configuration items defined, so the remaining ones are only field labels and names. Verification code special point, must be 6-bit characters, the code is as follows:

Items: [
	{
	    Fieldlabel: ' username ', name: ' UserName '
	},
	{
	    fieldlabel: ' Password ', name: ' Password ', InputType: "Password"
	},
	{
	    fieldlabel: "Authentication Code", Name: "Vcode", Minlength:6, Minlength:6
	}
]

Now consider how to display the verification code picture, if you add the image control directly inside the form, it will be difficult to control the location of the picture, because the best way is to set a container first. Because an instance of an IMG object is used when refreshing a picture, it is best to point to an object instance with a property, so that you can access the instance from within the class through the property. Add the following code to create the IMG object instance before creating the form:

Me.image=ext.create (ext.img,{
    src: "/verifycode"
});

Never create a form after you create it, or you cannot find an object when the table Tanne inserts a picture.

Code, the Verification code picture will be Verifycode controller generated, this temporarily down, will be discussed later.

Also to achieve is to click the Picture Refresh Verification code, but the search API found that the IMG object did not click the event. It doesn't matter, in the 4.1 version of Ext JS, modify the definition of the event, you can directly for the object generated HTML element binding event, as long as the listener event to add element configuration items on the line, this is quite a method. The following code can therefore be added to the configuration object that created the IMG instance:

listeners:{
    Click:me.onRefrehImage,
    element: "El",
	scope:me
}

In code, the El in the element configuration item represents the binding event in the HTML element that the object generates, the binding event being the Click event, and the event calling the Onrefrehimage method. method is simply refreshing the picture, so using the Setsrc method of the IMG object, you can complete the Onrefrehimage method by using the following code:

Onrefrehimage:function () {
    THIS.IMAGE.SETSRC ("/verifycode?_dc=" + (new Date ()). GetTime ());
}

The code is simple, using the Setsrc method to refresh the image of Src on the line, plus a timestamp to prevent the display of cached pictures.

OK, you can add the CAPTCHA image to the form items, the code is as follows:

{
    xtype: "Container", height:80, Anchor: "-5", Layout: "Fit",
    items: [Me.image]
}

As you can see from the code, the use of the container is to use fit layout to limit the size of the picture, so the layout is much easier. Also add a message to inform the user that the verification code is not case-sensitive, and if you do not see the code picture, click the picture to refresh the code as follows:

{
    xtype: "Container", Anchor: "-5", HTML: "* * Verify code is not case-sensitive, if you do not see the code, click the picture to refresh the verification code." "
}

The rest of the form is to add the login and reset button, and the code is as follows:

Dockeditems: [{
	xtype: ' Toolbar ', dock: ' Bottom ', UI: ' Footer ', layout: {pack: ' center '},
	items: [
	    {text: '] Login ", width:80, Disabled:true, Formbind:true, Handler:me.onLogin, scope:me},
	    {text: Reset, width:80, Handler:me . OnReset, Scope:me}
    ]
}]

The Dockeditems configuration item is used here for the purpose of introducing the new features of Ext JS 4, and the second is because it is really convenient to use this. The code defines a toolbar that is determined by the dock configuration item, here at the bottom (bottom), and the toolbar style uses the footer defined by the UI configuration item, which is the bottom footer toolbar of the original window, and the layout of the toolbar uses the center alignment.

The login button preset is disabled. The function of Formbind configuration is to use the button only if the form is entered in accordance with the requirements, this design is also new in Ext JS4, it is very convenient, no longer need to write code to achieve this. The login button invokes the Onlogin method. The reset button is simple, but simply calls the OnReset method.

The rest is done by Onlogin and OnReset methods. To complete the simple OnReset method, the basic function is to reset the form and move the focus to the first text field, which is the username, and to refresh the verification code as follows:

Onreset:function () {
    var me = this;
    Me.form.getForm (). reset ();
    if (Me.form.items.items[0]) {
        me.form.items.items[0].focus (true);
    }
    Me.onrefrehimage ();
}

The code takes note of the code that gets the first text field in the form, because after the form is instantiated, the items property points to the Mixedcollection instance because the text automatic object is found within its items. The next step is to onlogin the method, which is not very difficult, is to call the IsValid method first, verify that the form conforms to the submission request, and then invoke the Submit method submission. In fact, do not call IsValid also line, because the login button as long as the IsValid is true to use, but I am accustomed to, superfluous on the redundant point bar. The code is as follows:

Onlogin:function () {
    var me = this,
		f = me.form.getForm ();
    if (F.isvalid ()) {
        f.submit ({
            waitmsg: "Logging in, please wait ...",
            waittitle: "Login Now",
            success:function (form, Action) {
            	window.location.reload ();
            },
            failure:function () {
            },
            scope:me
        });
}

In the Submit method, Waitmsg and Waittitle will display a wait dialog box, and a mask to hide the form, not to allow the user to edit, where waitmsg is the message to display, Waittitle is the pop-up window title. However, in the 4.1.1 version, there are bugs, the author has submitted to the official forum, the correction method can refer to Http://www.sencha.com/forum/showthread.php?228970-4.1.1-GA-Form-Submit-Problem. Here the author is not fixed, the test will block the two code.

After a successful login (Success configuration entry), the page is refreshed to allow the page to write validation information to the cookie. Of course, you can jump to another page, but I think it is not as easy as this, this will be said later.

Login failure (Failure configuration entry), only one empty function is written because the form's submission returns the same data format, the same treatment, so you can use the same function for processing, but not yet written, so first leave an empty function.

Finally, do not forget to add the form to the items in the window, this must be placed before the call to Callparent, rather than initialize the form, the code is as follows:

Me.items = [Me.form]

At this point, the login window has been written for the time being, and today's progress is complete.

Hey, this kind of project progress will be depressing the project manager.

Lazy to upload the file, the following is the complete Login.js code:

<reference path= ". /ext.js "/> Ext.define" ("Ext.ux.Login", {extend: "Ext.window.Window", Singleton:true, Title: ' Simple CMS admin Department Background Login window ', width:400, height:400, Modal:true, Closable:false, Resizable:false, closeaction: ' H

        IDE ', Hidemode: ' Offsets ', initcomponent:function () {var me = this; Me.image = Ext.create (ext.img, {src: "/verifycode", listeners: {CLICK:ME.ONREFR

        Ehimage, element: "El", Scope:me}}); Me.form = Ext.create (Ext.form.Panel, {border:false, bodypadding:5, bodystyle: "Back
                Ground: #DFE9F6 ", url:" Account/login ", DefaultType:" TextField ", Fielddefaults: { LABELWIDTH:80, Labelseparator: ":", Anchor: "0", Allowblank:
		False}, items: [		{fieldlabel: "username", Name: "UserName"}, {fieldlabel: "password", Name: "Password", InputType: "PASSW Ord "}, {fieldlabel:" Authentication Code ", Name:" Vcode ", Minlength:6, Minlength:6}, {xtype:" Contai Ner ", height:80, Anchor:"-5 ", Layout:" Fit ", items: [Me.image]}, {xtype:" Container ", Anchor: "-5", HTML: "* * Verify code is not case-sensitive, if you do not see the verification code, click the picture to refresh the verification code." "}], Dockeditems: [{xtype: ' toolbar ', dock: ' Bottom ', UI: ' Footer ', layout: {pack: "Center"}, items: [{text: "Login", width:80, Disabled:true, Formbind:true, Handler:me.onLog

        In, Scope:me}, {text: "Reset", width:80, Handler:me.onReset, Scope:me}]});

    Me.items = [Me.form] me.callparent (arguments);
    }, Onrefrehimage:function () {THIS.IMAGE.SETSRC ("/verifycode?_dc=" + (new Date ()). GetTime ());
        }, Onreset:function () {var me = this;
        Me.form.getForm (). reset ();
        if (Me.form.items.items[0]) {Me.form.items.items[0].focus (true, 10);
    } me.onrefrehimage ();
        }, Onlogin:function () {var me = this, F = me.form.getForm ();
                if (F.isvalid ()) {F.submit ({waitmsg: "is logged in, please wait ...", Waittitle: "Log On",
                Success:function (form, action) {window.location.reload ();
        }, Failure:function () {}, scope:me}); }
    }


});



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.