You are on page 1of 27

Kết nối CSDL với ASPNET MVC

Cài đặt SQL Server 2019


 Link cài đặt https://www.microsoft.com/en-us/sql-
server/sql-server-downloads Chọn EXE để
cài đặt

 Chọn bản basic


 cài "SSMS" (SQL Server Management Studio) --> trình soạn
thảo kết nối tới sql server, link:
https://docs.microsoft.com/en-us/sql/ssms/download-sql-
server-management-studio-ssms?view=sql-server-ver15
Tạo CSDL
 Khởi đông SSMS 2019
 Tạo csdl có tên dbAspNet:
 Tạo bảng có tên tbl_account gồm 2 trường:
 username có kiểu nvarchar(50), pass có kiểu nvarchar(50)
 Nhập thông tin cho bảng tbl_account:
 username: admin, pass:123
 Tạo store procedure
 Tạo store procedure Sp_Acount_Login ALTER PROCEDURE [dbo].[Sp_Acount_Login]
 USE [db_asp] -- Add the parameters for the stored procedure
 GO here
 /****** Object: StoredProcedure @username nvarchar(50),
[dbo].[Sp_Acount_Login] Script Date: @pass nvarchar(50)
3/10/2022 8:34:05 AM ******/ AS
 SET ANSI_NULLS ON BEGIN
 GO -- SET NOCOUNT ON added to prevent extra
 SET QUOTED_IDENTIFIER ON result sets from
 GO -- interfering with SELECT statements.
 -- declare @count int
======================= declare @res bit
====================== select @count=count(*) from tbl_account
 -- Author:<Author,,Name> where username=@username and pass=@pass
 -- Create date: <Create Date,,> if @count>0
 -- Description:<Description,,> set @res=1
 -- else
======================= set @res=0
====================== select @res
END

Chọn excute để thực thi stored procedure


 Tạo project aspMVC có tên dbAspNet
 Copy 3 thư mục : assets, css, js của sb_min vào thư mục tainguyen
trên dbAspNet
 Tạo LoginController
 Tạo Index View của Login Controller

 Copy code file login.html vào file Index.cshtml


Tạo Project với tên Models

 Xóa class vừa tạo ra trong Models1 Project


Cài đặt EntityFramework cho Models
Project
 Kích phải lên Models Project/Manage NuGET packages…
Cài đặt EntityFramework
 Tạo thư mục Framework trong Models Project
 Kích phải lên thư mục Framework/add/New Item
Kiểm tra kết nối
đến database
 Code file acountModels.cs
 using Models.framework;
 using System.Data.SqlClient;

 namespace Models
 {
 public class acountModel
 {
 private dbcontext context = null;
 public acountModel()
 {
 context = new dbcontext();
 }
 public bool Login(string user, string pass)
 {
 object[] sqlParams =
 {
 new SqlParameter("@username",user),
 new SqlParameter("@pass",pass)

 };
 var res = context.Database.SqlQuery<bool>("Sp_Acount_Login @username,@pass", sqlParams).SingleOrDefault();
 return res;
 }
 }
 }
 Add references cho web dbAspNet
 Tạo class LoginModel.cs trong dbAspNet/Models
 File LoginModel.cs
 using System.ComponentModel.DataAnnotations;

 namespace dbAspNet.Models
 {
 public class LoginModel
 {
 [Required]
 public string UserName { set; get; }
 public string Password { set; get; }
 public bool RememberMe { set; get; }
 }
 }
 Tạo thư mục code để lưu thông tin session
 Tạo class UserSession.cs trong code

 public class UserSession


 {
 public string UserName { set; get; }
 }
 Tạo class SessionHelper.cs trong code
 Code file SessionHelper.cs
 public class SessionHelper
 {
 public static void SetSession(UserSession session)
 {
 HttpContext.Current.Session["loginSession"] = session;
 }
 public static UserSession GetSession()
 {
 var session = HttpContext.Current.Session["loginSession"];
 if (session == null)
 return null;
 else
 {
 return session as UserSession;
 }
 }
 }
 File LoginController.cs
 using Models;
 using dbAspNet.code;

 namespace dbAspNet.Controllers
 {
 public class LoginController : Controller
 {
 // GET: Login
 [HttpGet]
 public ActionResult Index()
 {
 return View();
 }
 [HttpPost]
 [ValidateAntiForgeryToken]
 public ActionResult Index(LoginModel model)
 {
 var result = new acountModel().Login(model.UserName, model.Password);
 if(result&& ModelState.IsValid)
 {
 SessionHelper.SetSession(new UserSession() { UserName = model.UserName });
 return RedirectToAction("Index","Home");
 }
 else
 {
 ModelState.AddModelError("","Tên đăng nhập hoặc mật khẩu không đúng");
 }
 return View(model);
 }
 }
 }
 Code file index.cshtm của Controller Login
 @using (Html.BeginForm())
 {
 @Html.AntiForgeryToken()
 @Html.ValidationSummary(true,null,new {@class="alert alert-danger" })
 <div class="form-floating mb-3">
 @Html.TextBoxFor(model=>model.UserName,new { @class= "form-
control",@placeholder="UserName",@autofocus="autofocus" })


 </div>
 <div class="form-floating mb-3">
 @Html.TextBoxFor(model => model.Password, new { @class = "form-
control", @placeholder = "Password", @type = "password" })
 </div>
 <div class="form-check mb-3">
 <label>
 @Html.CheckBoxFor(model=>model.RememberMe)
 Remember me
 </label>
 </div>
 Copy chuỗi kết nối trong file App.Config của Models project
 <connectionStrings>
 <add name="dbcontext" connectionString="data
source=LAPTOP-AU5V7T6G;initial catalog=db_asp1;integrated
security=True;MultipleActiveResultSets=True;App=EntityFram
ework" providerName="System.Data.SqlClient" />
 </connectionStrings>
 Dán vào file web.config của dbAspNet, sau cặp thẻ
<configSections> …</configSections>
 <connectionStrings>
 <add name="dbcontext" connectionString="data
source=LAPTOP-AU5V7T6G;initial catalog=db_asp1;integrated
security=True;MultipleActiveResultSets=True;App=EntityFram
ework" providerName="System.Data.SqlClient" />
 </connectionStrings>

You might also like