Professional Documents
Culture Documents
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
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>