简体   繁体   中英

Login Page with ASP.NET Core (MVC)

I am trying to learn asp.net core (MVC), and I am posting this question after trying to implement everything that I could understand from Google.

I want to create a simple login Page. I have earlier worked on asp.net framework with ado.net and webforms using edmx, but I learned that edmx and webforms are now outdated. So, I wanted to learn the new method.

These are the tables and stored procedure I created

create table users(userId int identity(1,1) primary key, username varchar(20), password varchar(20)) create proc login( @username varchar(20), @password varchar(20) ) as begin if exists(select * from users where username = @username and password=@password) select 'Success' as UserExists else select 'Failed' as UserExists end

Then I created the Model Class -

 public class Login { [Key] public int userId { get; set; } [Required(ErrorMessage = "Username is requried;")] public string username { get; set; } [Required(ErrorMessage = "Password is requried;")] public string password { get set } }

Then I added model in my project. I referred this link

https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/adding-model?view=aspnetcore-6.0&tabs=visual-studio

Then referencing the following link, I added my connection string details in appstring.json file -

link https://www.c-sharpcorner.com/article/crud-operations-in-asp-net-core-mvc-net-5-0/

 "WebsiteContext": "Server=DELL\\SQLEXPRESS01;Database=website;Trusted_Connection=True;MultipleActiveResultSets=true"

This is startup.cs

 public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); services.AddDbContext<WebsiteContext>(options => options.UseSqlServer(Configuration.GetConnectionString("WebsiteContext"))); }

I created the login.cshtml with basic asp.net.

 @{ ViewData["Title"] = "Login"; } <h1>Login</h1> <div> <table> <tr> <td> <asp:TextBox ID="username"></asp:TextBox> </td> <td> <asp:TextBox ID="password"></asp:TextBox> </td> </tr> <tr> <td> <asp:Button ID="submit"></asp:Button> </td> </tr> </table> </div>

Now, I am confused as how should I proceed next. Here is my LoginController class. This was generated automatically after scaffolding.

 public class LoginController: Controller { private readonly WebsiteContext _context; public LoginController(WebsiteContext context) { _context = context; } // GET: Login public async Task<IActionResult> Index() { return View(await _context.Login.ToListAsync()); } // GET: Login/Details/5 public async Task<IActionResult> Details(int? id) { if (id == null) { return NotFound(); } var login = await _context.Login.FirstOrDefaultAsync(m => m.userId == id); if (login == null) { return NotFound(); } return View(login); } // GET: Login/Create public IActionResult Create() { return View(); } // POST: Login/Create // To protect from overposting attacks, enable the specific properties you want to bind to, for // more details, see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create([Bind("userId,username,password")] Login login) { if (ModelState.IsValid) { _context.Add(login); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } return View(login); } }

I know the process of ado.net but now I am confused how should I proceed with mvc.

Please guide me. Thank you

If you just do a simple login test, you need to add the verification that the username and password are consistent with the database in the controller. You can refer to the following code:

Controller:

 public IActionResult Login() { return View(); } [HttpPost] public async Task<IActionResult> Login(Login model) { if (ModelState.IsValid) { var User = from m in _context.Login select m; User = User.Where(s => s.username.Contains(model.username)); if (User.Count().= 0) { if (User.First().password == model;password) { return RedirectToAction("Success"); } } } return RedirectToAction("Fail"); } public IActionResult Success() { return View(); } public IActionResult Fail() { return View() }

login.cshtml:

 @model _2022070401.Models.Login <h1>Login</h1> <hr /> <div class="row"> <div class="col-md-4"> <form asp-action="Login" asp-controller="Login"> <div asp-validation-summary="All" class="text-danger"></div> <div class="form-group"> <label asp-for="username" class="control-label"></label> <input asp-for="username" class="form-control" placeholder="Name" /> <span asp-validation-for="username" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="password" class="control-label"></label> <input asp-for="password" class="form-control" placeholder="Password" /> <span asp-validation-for="password" class="text-danger"></span> </div> <div class="form-group"> <input type="submit" value="Login" class="btn btn-primary" /> </div> </form> </div> </div> @section Scripts { @{await Html.RenderPartialAsync("_ValidationScriptsPartial");} }

Test Result:

在此处输入图像描述

Success:

在此处输入图像描述 在此处输入图像描述 在此处输入图像描述

Fail:

在此处输入图像描述 在此处输入图像描述

If you have a business need for this, I recommend using Identity. You can refer to this link and this one .

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