Anda di halaman 1dari 7

In this post I want to show you how to use jQuery to create an AJAX login screen.

I am going to
use an ASP.NET MVC application for this demonstration. I will be modifying the small default
application that is created when you create a new MVC application. So go ahead and create a
new MVC application. I will be walking through the process step by step so when this article is
done you will have a working application.

Step 1

Open LogOnUserControl.ascx. This is found in /Views/Shared/. What we want to do is modify


the link to include an onclick attribute which will fire the login() event handler and assign an id
to the link. The code should look like this:

<%= Html.ActionLink("Log On", "LogOn", "Account", null,


new { onclick = "return login();", id = "login_link" })%>

Step 2

Open the Site.Master master page, also located in /Views/Shared/, add  the links to our
stylesheet, jQuery, and our JavaScript file in the head section of the document.
<link type="text/css" rel="stylesheet" href="../../Content/login.css" />
<script type="text/javascript" src="../../Scripts/jquery-1.2.6.min.js"></script>
<script type="text/javascript" src="../../Scripts/login.js"></script>

Go ahead and create a login.css file in /Content/ and a login.js file in /Scripts/. Leave them empty
for now.

Step 3

While still in Site.Master, add the following code at the bottom of the page, just before the
closing body tag. This is our login form that we will use. The code contains a div element with
the id lightbox that will cover the screen to make our login form act as a model dialog. The
lightbox will be a transparent black color.

In addition to the form input elements there is also a div element called message that will server
as an area for us to output messages.

<div id="lightbox"></div>
<div id="login_outer_container">
<div id="login_form">
<div id="message"></div>
<fieldset>
<legend>Login Information</legend>
<p>
<label for="username">Username:</label>
<%
= Html.TextBox("username")

%>

<%

= Html.ValidationMessage("username")

%>

</p>

<p>
<label for=”password”>Password:</label>

<%

= Html.Password("password")

%>

<%

= Html.ValidationMessage("password")

%>

</p>

<p>

<%

= Html.CheckBox("rememberMe")

%> <label class=”inline” for=”rememberMe”>Remember me?</label>

</p>

<p>

<input type=”button” value=”Log On” onclick=”submitForm();” />

<input type=”button” value=”Cancel” onclick=”cancelLogin();” />

</p>
</fieldset>

</div>

</div>

Step 4

Add the following code to login.css. This will style our form elements.

#lightbox {
position: absolute;
top: 0;
left: 0;
width: 100%;
background: black;
filter: alpha(opacity=60);
opacity: 0.6;
display: none;
}
 
#login_outer_container {
position: absolute;
top: 50%;
left: 50%;
}
 
#login_form {
position: relative;
top: -125px;
left: -200px;
width: 400px;
height: 250px;
display: none;
background: white;
padding: 10px;
border: 1px solid #424242;
}
#message {
display: none;
border: 1px solid #b8b8b8;
background: #f6f3f6;
padding: 5px;
color: Red;
}
 
 

Step 5

Alright, this is where the real magic happens. We are going to add code to login.js. I will go slow
and explain what each function is doing and why it matters to our application.

The first function we are going to add is the login() event handler we mentioned earlier in the
post. In this function we are getting the lightbox element and assigning some stylesheet
properties to it. Notice that we are setting the filter attribute even thought we did so in login.css.
For some reason IE keep losing this setting so we had to add it again. We are also telling
lightbox to fade in slowly.

Next we get the main login form element and tell it to also fade in slowly.

Finally, we return false to prevent the link from jumping to it’s href value. We don’t want to
cause a page refresh.

function login() {
$('#lightbox')
.css({
'height': $(document).height(),
//reset opacity because IE loses it on open
'filter': 'alpha(opacity=60)'
})
.fadeIn('slow');
$('#login_form').fadeIn('slow');
return false;
}

Now when a user clicks the [ Log On ] link an impressive login form will fade into the center of
the screen.

Notice how we set the height of the lightbox to the current height of the document. If the user
resizes the browser window this will cause the lightbox to be too big and add scroll bars or cause
the lightbox to be too small, all depending how the window is resized. To fix this this problem
we will create a function that will set lightbox to the current height of the document and setup an
event handler that will fire our function every time the window is resized.

function adjustLightbox() {
$('#lightbox').css({ 'height': $(document).height() });
};
 
var resizeTimer = null;
$(window).bind('resize', function() {
if (resizeTimer) clearTimeout(resizeTimer);
resizeTimer = setTimeout(adjustLightbox, 100);
});
 
When we created our login form markup we added an input button that had an onclick handler
called cancelLogin(). If the user clicked this button we wanted to cancel the login form, clear an
input, and restore the main screen. Let’s create that function.

This function first tells lightbox and the main login form to slowly fade out which will restore
the main screen.

Next we clear the value of all input elements that are not buttons and make sure the remember
me checkbox is not checked.

Lastly, we clear and messages that were output and hide the message element.

function cancelLogin() {
$('#lightbox').fadeOut('slow');
$('#login_form').fadeOut('slow');
$('#login_form input[type!=button]').val('');
$('#login_form input[type=checkbox]').each(function(i) {
this.checked = false;
});
$('#message').html('').css({ 'display' : 'none' });
}

This brings us to out last function which will submit the form when the user clicks submit. First
create the submitForm function. This function has been assigned to the submit button’s onclick
handler in our HTML.

function submitForm() {
 
}
 

The first thing we need to do is get the values from our three form elements, username,
password, and remember me.

var username = $('#username').value;


var password = $('#password').value;
var rememberMe = $('#rememberMe').checked ? 'true' : 'false';

At this point you can do any form validation you want against the values. I am not going to
include any validation in this demonstration.

Next we’ll build a data string out of our three values.

var dataString = 'username=' + username + '&password=' + password + '&rememberMe='


+ rememberMe;

Finally we will setup our AJAX call to the server to authenticate the user. We will use the data
string we just setup as the data to pass to the request. We have also setup success and failure
callbacks.
If the request succeeds we will call the cancelLogin() function to close the login form and change
the Log On link to say Log Off.

If the request fails, we’ll show the user an error message.

1: $.ajax({
2: type: 'POST',
3: url: '/Account/LogOn',
4: data: dataString,
5: success: function() {
6: cancelLogin();
7: $('#login_link').html('Log Off').href = '/Account/LogOff';
8: },
9: error: function() {
10: $('#message').html('Failed to login')
11: .css({ 'display': 'block' });
12: }
13: });

That pretty much finishes things off. you should now have a working login form. Stayed tuned
for more great posts from Dev102.com by grabbing the RSS feed. You can also see more posts I
have written on my blog or grab my RSS feed.

Anda mungkin juga menyukai