简体   繁体   中英

Allow Login using Username or Email and password in MVC

I am new to MVC. I want to create Text-box username or email based on that user entered. I need to check with a database. How can I achieve that?

Login View

  @Html.TextboxFor(d=>d.username,new{@class="form-control"})

  @Html.TextboxFor(d=>d.password,new{@class="form-control"})

Model class

public string username {get;set;}
public string password {get;set;}
public string Email {get;set;}

I don't want to create another Field for Email. During login check, I want to check username/email both, if any of them is true, then allow a respective user to log in.

You can achieve it by too many ways. You can also use asp.net membership. https://www.c-sharpcorner.com/UploadFile/4d9083/using-membership-in-Asp-Net-mvc-4/

When you are verifying valid user on "Login" button click, just need to check the username and email both.

Just follow simple steps: 1) Name this view as Login.cshtml

@model YourNameSpace.Models.Login

@using (Html.BeginForm("Index", "Sample", FormMethod.Post, new { enctype = "multipart/form-data" })) { @Html.ValidationSummary(true)

  @Html.TextboxFor(d=>d.username,new{@class="form-control"}) @Html.TextboxFor(d=>d.password,new{@class="form-control"}) 

}

2) And in your Index Action of Sample Controller:

  [HttpPost] public ActionResult Index(Login login) { if (ModelState.IsValid) { string con = "YOUR CONNECTION STRING"; SqlCommand cmd = new SqlCommand("select * from Users where username=@username and password=@password ", con); cmd.Parameters.AddWithValue("@username", login.Username); cmd.Parameters.AddWithValue("@password", login.Password); con.Open(); SqlDataReader dr = default(SqlDataReader); dr = cmd.ExecuteReader(CommandBehavior.CloseConnection); while ((dr.Read()) == true) { lbluser.Text = dr["UserName"].ToString(); lblpwd.Text = dr["password"].ToString(); } dr.Close(); con.Close(); } return RedirectToAction("Index"); } 

Please make sure con is the connection string that points to the database and Users is your table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM