如何使用Bootstrap Modal和jQuery AJAX创建登录功能

by Yogi

由瑜伽士

Bootstrap Modal is an excellent way to create a Login form on your website. In this tutorial, you will learn how to create a login feature using Bootstrap for an ASP.NET website. The login Check feature will be created using jQuery AJAX.

Bootstrap Modal是在您的网站上创建登录表单的绝佳方法。 在本教程中,您将学习如何使用Bootstrap为ASP.NET网站创建登录功能。 登录检查功能将使用jQuery AJAX创建。

I will create the following features Step by Step:

我将逐步创建以下功能:

1. A Bootstrap Modal that will contain a login form.

1.一个Bootstrap Modal,它将包含一个登录表单。

2. The Login Form will contain 2 fields, ‘Username’ & ‘Password’. The user has to enter their values in these fields.

2.登录表单将包含2个字段,“用户名”和“密码”。 用户必须在这些字段中输入其值。

3. On clicking the submit button on the form, the user’s input (username and password) will be sent to the C# function.

3.单击表单上的提交按钮后,用户的输入(用户名和密码)将被发送到C#函数。

4. This C# function will check whether the username and password are correct or not.

4.此C#函数将检查用户名和密码是否正确。

5. If they are correct then the user is redirected to the profile page.

5.如果正确,则将用户重定向到配置文件页面。

您可以在此处查看有效的DEMO(You can check out the working DEMO here.)
使用登录表单创建Bootstrap模式 (Creating a Bootstrap Modal with a Login Form)

Add the reference of “bootstrap CSS, jQuery and bootstrap js” files on the page head.

在页面标题上添加“ bootstrap CSS,jQuery和bootstrap js”文件的引用。

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

Next Create a Bootstrap Modal that contains the login form:

接下来,创建一个包含登录表单的Bootstrap Modal:

<div class="container"><div class="validCredential">
<h3>Try any one of the following three:</h3><div><p>  1. Username: Ram</p><p>  Password: admin</p></div>
<div><p>  2. Username: Shiv</p><p>  Password: admin</p></div>
<div><p>  3. Username: Krishna</p>
<p>  Password: admin</p></div>
</div>
<!-- The button that triggers the Modal --><button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>
<!-- Bootstrap Modal --><div id="myModal" class="modal fade" role="dialog">  <div class="modal-dialog">
<!-- Modal content-->    <div class="modal-content">      <div class="modal-header">        <button type="button" class="close" data-dismiss="modal">×</button>        <h4 class="modal-title">Log in with your Username</h4>      </div>
<div class="modal-body">        <table>          <tbody>            <tr>              <td>                <input type="text" id="userNameTextBox" placeholder="Username" />              </td>            </tr>            <tr>              <td>                <span id="userNamSpan"></span>              </td>            </tr>            <tr>              <td>                <input type="text" id="passwordTextBox" placeholder="Password" />              </td>            </tr>            <tr>              <td>                <span id="passwordSpan"></span>              </td>            </tr>            <tr>              <td>                <input type="button" id="submitButton" value="Login" />              </td>            </tr>            <tr>              <td>                <span id="messageSpan"></span>              </td>            </tr>            <tr>              <td>                <img id="loadingImg" src="loading.gif" />              </td>            </tr>          </tbody>        </table>      </div>
<div class="modal-footer">      <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>    </div>  </div><!-- END Modal content--></div>
</div>
<!-- END Bootstrap Modal --></div>

This is how the bootstrap modal login form will look.

这是引导模式登录表单的外观。

在按钮单击事件上添加jQuery代码 (Adding the jQuery Code on the button click event)

In the button click, I will force users to enter some value to the username and password fields, before they submit the form.

在单击按钮时,我将强制用户在提交表单之前在用户名和密码字段中输入一些值。

When both the textboxes contain some value, only then I will be calling the C# function using the jQuery AJAX method. With this method, I will be able to pass the values of the 2 text boxes (username and password) to my C# function.

当两个文本框都包含某个值时,只有这样,我才会使用jQuery AJAX方法调用C#函数。 使用这种方法,我将能够将2个文本框(用户名和密码)的值传递给C#函数。

Add the below jQuery code to your page:

将以下jQuery代码添加到您的页面:

$("#submitButton").click(function (e) {
if ($("#userNameTextBox").val() == "")
$("#userNamSpan").text("Enter Username");
else
$("#userNamSpan").text("");
if ($("#passwordTextBox").val() == "")
$("#passwordSpan").text("Enter Password");
else
$("#passwordSpan").text("");
if (($("#userNameTextBox").val() != "") && ($("#passwordTextBox").val() != ""))
$.ajax({  type: "POST",  url: "index.aspx/login",  contentType: "application/json; charset=utf-8",  data: '{"username":"' + $("#userNameTextBox").val() + '","password":"' + $("#passwordTextBox").val() + '"}',  dataType: "json",  success: function (result, status, xhr) {    if (result.d == "Success") {      $("#messageSpan").text("Login Successful, Redireting to your profile page.");      setTimeout(function () { window.location = "profile.aspx"; }, 2000);    }    else      $("#messageSpan").text("Login failed, Please try again.");    },   error: function (xhr, status, error) {     $("#dbData").html("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText)   }});
});
$(document).ajaxStart(function () {  $("#loadingImg").show();});
$(document).ajaxStop(function () {  $("#loadingImg").hide();});

In the success callback method, you can see that I am redirecting the user to the profile.aspx page if-and-only-if I receive the “Success” message.

在成功回调方法中,您可以看到,如果我收到“ 成功 ”消息,则将用户重定向到profile.aspx页。

The setTimeout() is a JavaScript function that will redirect to the profile page in 2 seconds.

setTimeout()是一个JavaScript函数,它将在2秒内重定向到个人资料页面。

The following 2 images will explain the login feature:

以下两个图像将说明登录功能:

1. When login fails.

1.登录失败时。

2. When login is successful.

2.登录成功后。

C#代码: (The C# code:)

Now in your .aspx.cs page, add the following code:

现在,在您的.aspx.cs页中,添加以下代码:

[System.Web.Services.WebMethod]
public static string login(string username, string password)
{
var cred = LoadCredential();
var count = (from t in cred
where t.username == username && t.password == password
select t).Count();
if (count == 1)
{
HttpContext.Current.Session["User"] = username;
return "Success";
}
else
return "Failed";
}
class Credential
{
public string username { get; set; }
public string password { get; set; }
}
static List<Credential> LoadCredential()
{
List<Credential> credList = new List<Credential>();
Credential cred = new Credential();
cred.username = "Ram";
cred.password = "admin";
credList.Add(cred);
cred = new Credential();
cred.username = "Shiv";
cred.password = "admin";
credList.Add(cred);
cred = new Credential();
cred.username = "Krishna";
cred.password = "admin";
credList.Add(cred);
return credList;
}

The login() function is the one that is called by the jQuery method. It checks if the username and passwords are correct and then returns the appropriate message.

login()函数是jQuery方法调用的函数。 它检查用户名和密码是否正确 ,然后返回适当的消息。

CSS (CSS)

To style the login form and the bootstrap modal so that they look perfect, add the following CSS to your page:

要设置登录表单和引导程序模式的样式以使其看起来完美,请在页面中添加以下CSS:

.btn {
margin: 15px 0;
}
#loadingImg {
display: none;
position: absolute;
margin: auto;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
.validCredential h3 {
float: left;
text-decoration: underline;
}
.validCredential div {
clear: both;
}
.validCredential p {
float: left;
padding-right: 10px;
}
::-webkit-input-placeholder {
color: #ccc;
}
#myModal {
color: #1fa67b;
}
#myModal table {
position: relative;
margin: auto;
}
#myModal table input {
border-radius: 5px;
border: solid 1px #CCC;
margin: 10px;
padding: 3px 10px;
color: #000;
}
#myModal table input[type="button"] {
width: 94%;
background: #1fa67b;
color: #FFF;
}
#myModal table span {
float: left;
font-size: 12px;
color: #f00;
padding-left: 23px;
}
个人资料页 (Profile Page)

On the profile page, the user will get the welcome message. The code of the profile page is the following:

在个人资料页面上,用户将收到欢迎消息。 个人资料页面的代码如下:

<h1 id="welcomeMessage" runat="server"></h1>
if (!IsPostBack){  welcomeMessage.InnerHtml = "Welcome " + Session["User"] + " to the profile page.";}

Check out the working demo by clicking the below link:

点击下面的链接,查看有效的演示:

工作演示 (Working DEMO)

结论 (Conclusion)

I hope you liked this tutorial. Feel free to contact me for any questions. I will be there to help if you need it. If you liked this tutorial, then kindly share it on your social accounts.

希望您喜欢本教程。 如有任何问题,请随时与我联系。 如果您需要,我会在那里帮助您。 如果您喜欢本教程,请在您的社交帐户上分享。

I have also published another tutorial on freeCodeCamp, you would like to see it too — Master the art of looping in JavaScript with these incredible tricks

我还在freeCodeCamp上发布了另一篇教程,您也希望看到它- 用这些不可思议的技巧来掌握JavaScript循环的艺术

翻译自: https://www.freecodecamp.org/news/how-to-create-a-login-feature-with-bootstrap-modal-and-jquery-ajax-53dc0d281609/

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值