Cộng đồng chia sẻ tri thức Lib24.vn

Bài giảng và bài tập lập trình WEB 2

e6ef71125f308b76487b7ed11c22cf99
Gửi bởi: Khoa CNTT - HCEM 9 tháng 8 2020 lúc 0:23:26 | Được cập nhật: 5 tháng 5 lúc 14:28:44 Kiểu file: DOCX | Lượt xem: 896 | Lượt Download: 17 | File size: 79.170324 Mb

Nội dung tài liệu

Tải xuống
Link tài liệu:
Tải xuống

Các tài liệu liên quan


Có thể bạn quan tâm


Thông tin tài liệu














Trường Cao đẳng Cơ Điện Hà Nội – 160 Mai dịch, Cầu giấy, Hà Nội

KHOA CNTT. Website: http://cntt.codienhanoi.edu.vn

BÀI 1: THIẾT KẾ CSDL QUẢN LÝ BÁN HÀNG ONLINE

Tạo Database BanhangOnline gồm các bảng sau:

  1. About

  1. Category

  1. Contact

  1. Content

  1. ContentTag.

  1. Feedback

  1. Footer

  1. Menu

  1. MenuType

  1. Product

  1. ProductCategory

  1. Role

  1. Slide

  1. Tag

  1. User

  1. UserGroup

17. Company

18. News

BÀI 2: TẠO MỚI PROJECT VÀ CÁCH SỬ DỤNG LAYOUT VÀ SESSION

1. Tạo mới Project.

Bước 1: Khởi động VS Express 2015 for web:

Bước 2: File New Project

2. Tương tác giữa Model – View – Controller.

+Sử dụng ViewBag

Bước 1: Mở Controller để xây dựng ViewBag:

Bước 2: Sử dụng ViewBag đã được xây dựng.

+Sử dụng Models

Bước 1: Tạo Model

Bước 2: Xậy dựng trong Controller.

Bước 3: Viết trong View

3. Tạo mới và sử dụng Areas

-Tạo mới

Phải chuột lên Project BanghangOnline Add Area…

Đặt tên: Admin

Sau khi thêm thành công:

- Sử dụng

Tạo mới 1 HomeController.

Thêm mới 1 View

Chạy chương trình:

Nếu như bạn chạy từ trang chủ bên ngoài chương trình sẽ báo lỗi. Lúc này bạn cần phải sửa ở trong file RouteConfig.cs

Thêm đoạn code sau:

defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }, namespaces: new[] { "BanHangOnline.Controllers" }

4. Sử dụng template.

Bước 1: Download và giải nén:

Bước 2: Copy thư mục vừa tạo vào Project.

-Trong Project BanhangOnline tạo mới 1 thư mục Assets (chứa tài nguyên)

-Tạo mới thư mục Assets\Admin

Copy các thư mục vào Assets\Admin

Bước 3: Vào thư mục Pages mở file Index ở chế độ Edit

Copy toàn bộ code

Bước 4: Dán vào View Index của Admin

Bước 5: Thay đổi đường dẫn đến thư mục /Assets/Admin

Bước 6: Chạy chương trình:

5. Sử dụng Layout, RenderBody(), RenderSection()

- Tạo và sử dụng Layout và RenderBody().

Bước 1: Tạo_Layout.cshtml trong thư mục share của Admin.

Bước 2: Vào trang index cắt toàn bộ đoạn code và dán vào trang _Layout:

Bước 3: Trong trang _Layout thu gọn lại code, tìm đến thẻ page-wrapper

Cắt đoạn code đó và thay thế @RenderBody()

Bước 4: Qua trang Index

Dán đoạn code vừa cắt ở bước 3, đồng thời thêm dòng

Layout = "~/Areas/Admin/Views/Shared/_Layout.cshtml";

Bước 5: Chạy chương trình.

- Sử dụng RenderSection().

Bước 1: Định nghĩa Section. Tại _Layout.cshtml (Các bạn định nghĩa ở vị trí nào thì sau khi chương trình chạy sẽ thể hiện Html tại vị trí đó)

@RenderSection("Header",required:false)

Bước 2: Sử dụng Section sau khi đã định nghĩa. Qua trang Index

@section Header{"Đây là trang chủ Admin"}

6. Sử dụng RenderPage để chia nhỏ Layout.

Bước 1: Tạo mới 1 View trong thư mục Shared _Navigation.cshtml.

Bước 2: Qua _Layout.cshtml tìm đến Navigation

Cắt (Ctrl+X) và dán vào _Navigation.cshtml

Bước 3: Tại vị trí vừa cắt trong _Layout.cshtml ta thêm dòng lệnh

@RenderPage("_Navigation.cshtml")

Sửa lại giao diện cho trang chủ (Admin) theo mẫu sau:

BÀI 3: KẾT NỐI CSDL VÀ TẠO TRANG ĐĂNG NHẬP.

1. Tạo kết nối CSDL với Code First from Database

Bước 1: Tạo mới 1 Project: Phải chuột lên Solution Add New project ClassLibrary Đặt tên: KetNoiCSDL

Bước 2: Tạo 2 Thư mục EF, DAO trong KetNoiCSDL

Bước 3: Thêm ADO.NET vào EF. Phải chuột lên EF Add New item

Đặt tên: BanhangOnlineDbContext

Kích Add. Chọn Code First From Database

Kích Next

Chọn New Connection

Thiết lập các thông số, kích Test Connection

Chọn Yes,…

Lựa chọn các bảng như trên.

Bước 4: Thêm chuỗi kết nối vào web.config

Mở file App.Config. Copy 3 dòng dưới

Mở file Web.Config dán vào như hình dưới

2. Tạo trang đăng nhập.

Bước 1: Trong thư mục DAO, tạo mới lớp UserDao.cs

Chọn Class và đặt tên UserDao.cs Add

Viết code như sau:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using KetNoiCSDL.EF;

namespace KetNoiCSDL.DAO

{

public class UserDao

{

BanhangOnlineDbContext db = null;

public UserDao()

{

db = new BanhangOnlineDbContext();

}

public bool Login(String UserName, string PassWord)

{

var res = db.User.Count(x => x.UserName == UserName && x.Password == PassWord);

if (res > 0)

{

return true;

}

else

{

return false;

}

}

public User GetByID(string userName)

{

return db.User.SingleOrDefault(x => x.UserName == userName);

}

}

}

Bước 2: Thêm Reference KetNoiCSDL vào trong BanhangOnline

Phải chuột lên ReferencesAdd Reference

Bước 3: Trong Areas\Admin\Models Tạo LoginModel.cs

Viết code như sau:

using System;

using System.Collections.Generic;

using System.ComponentModel.DataAnnotations;

using System.Linq;

using System.Web;

namespace BanHangOnline.Areas.Admin.Models

{

public class LoginModel

{

[Required(ErrorMessage ="Mời bạn nhập Username.")]

public string UserName { set; get; }

[Required(ErrorMessage = "Mời bạn nhập Password.")]

public string PassWord { set; get; }

public bool RememberMe { set; get; }

}

}

Bước 4: Tạo thư mục Common:

Tạo mới 2 Class: UserLogin.cs và CommonConstants.cs:

Viết Code cho UserLogin.cs như sau :

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

namespace BanHangOnline.Common

{

[Serializable]

public class UserLogin

{

public long UserID { set; get; }

public string UserName { set; get; }

}

}

Viết code cho CommonConstants.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

namespace BanHangOnline.Common

{

public static class CommonConstants

{

public static string USER_SESSION = "USER_SESSION";

}

}

Bước 5: Viết code cho LoginController.cs

using BanHangOnline.Areas.Admin.Models;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using KetNoiCSDL.DAO;

using BanHangOnline.Common;

namespace BanHangOnline.Areas.Admin.Controllers

{

public class LoginController : Controller

{

// GET: Admin/Login

public ActionResult Index()

{

return View();

}

public ActionResult Login(LoginModel model)

{

if(ModelState.IsValid)

{

var dao = new UserDao();

var res = dao.Login(model.UserName, model.PassWord);

if(res)

{

var user = dao.GetByID(model.UserName);

var userSession = new UserLogin();

userSession.UserName = user.UserName;

userSession.UserID = user.ID;

Session.Add(CommonConstants.USER_SESSION, userSession);

return RedirectToAction("Index", "Home");

}

else

{

ModelState.AddModelError("", "Đăng nhập không đúng.");

}

}

return View("Index");

}

}

}

Bước 6: Thêm mới trang Index của Login:

Copy toàn bộ code trong trang Login.html (trong template mà bạn vừa down về) dán vào trang Index của login. Thay đổi đường dẫn:

Bước 7: Sửa lại trang Index của Login như sau:

Khai báo thêm:

@model BanHangOnline.Areas.Admin.Models.LoginModel

Sửa lại code:

<div class="panel-div">

@using (Html.BeginForm("Login", "Login", FormMethod.Post))

{ <fieldset>

<div class="form-group">

@Html.TextBoxFor(model => model.UserName, new { @class = "form-control", @autofocus = "autofocus" })

</div>

<div class="form-group">

@Html.PasswordFor(model => model.PassWord, new { @class = "form-control" })

</div>

<div class="checkbox">

<label>

@Html.CheckBoxFor(model => model.RememberMe) RememberMe

</label>

</div>

<!-- Change this to a button or input when using this as a form -->

<button type="submit" class="btn btn-lg btn-success btn-block">Login</button>

</fieldset>

}

</div>

Bước 8: Chạy chương trình.

Bước 9: Cài đặt Entity Framework

BÀI 4: MÃ HÓA MD5 VÀ NÂNG CẤP TRANG LOGIN.

1. Mã hóa MD5 cho trường Password.

Bước 1: Tạo class MaHoaMd5.cs vào trong thư mục Common.

Viết code cho class MaHoaMd5.cs:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Security.Cryptography;

using System.Text;

using System.Web;

namespace BanHangOnline.Common

{

public class MaHoaMd5

{

public static string MD5Hash(string text)

{

MD5 md5 = new MD5CryptoServiceProvider();

//compute hash from the bytes of text

md5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(text));

//get hash result after compute it

byte[] result = md5.Hash;

StringBuilder strBuilder = new StringBuilder();

for (int i = 0; i < result.Length; i++)

{

//change it into 2 hexadecimal digits

//for each byte

strBuilder.Append(result[i].ToString("x2"));

}

return strBuilder.ToString();

}

}

}

Các bạn có thể tìm kiếm phương thức mã hóa này trên mạng như sau:

Copy đoạn code sau và dán vào class MaHoaMd5.cs:

Bước 2: Mở LoginController.cs sửa lại code:

var res = dao.Login(model.UserName, MaHoaMd5.MD5Hash(model.PassWord));

Bước 3 : Vào trang Md5online

Mở User của CSDL copy Password vào trang Md5online để được mã hóa

Copy dán lại vào trường Password:

Bước 4: Chạy thử chương trình.

2. Nâng cấp trang đăng nhập (Login)

Bước 1: Mở UserDao.cs sửa lại code:

public int Login(String UserName, string PassWord)

{

var res = db.User.SingleOrDefault(x => x.UserName == UserName);

if (res == null)

{

return 0;

}

else

if (res.Status == false)

{

return -1;

}

else

{

if (res.Password == PassWord)

return 1;

else

return -2;

}

}

Bước 2: Mở LoginController.cs sửa lại:

using BanHangOnline.Areas.Admin.Models;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using KetNoiCSDL.DAO;

using BanHangOnline.Common;

namespace BanHangOnline.Areas.Admin.Controllers

{

public class LoginController : Controller

{

// GET: Admin/Login

public ActionResult Index()

{

return View();

}

public ActionResult Login(LoginModel model)

{

if (ModelState.IsValid)

{

var dao = new UserDao();

var res = dao.Login(model.UserName, MaHoaMd5.MD5Hash(model.PassWord));

if (res == 1)

{

var user = dao.GetByID(model.UserName);

var userSession = new UserLogin();

userSession.UserName = user.UserName;

userSession.UserID = user.ID;

Session.Add(CommonConstants.USER_SESSION, userSession);

return RedirectToAction("Index", "Home");

}

else if (res == 0)

{

ModelState.AddModelError("", "Tài khoản không tồn tại.");

}

else if (res == -1)

{

ModelState.AddModelError("", "Tài khoản đang bị khóa.");

}

else if (res == -2)

{

ModelState.AddModelError("", "Mật khẩu không đúng.");

}

else

{

ModelState.AddModelError("", "Đăng nhập không đúng.");

}

}

return View("Index");

}

}

}

Bước 3: Vào trang index của login thêm dòng lệnh :

@Html.ValidationSummary(false, "", new { @class = "text-danger" });

Bước 4: Chạy chương trình:

BÀI 5: KIỂM TRA SESSION TRONG ADMIN

Khi người dùng muốn bỏ qua login, mà chuyển đến trang chủ. Thì website phải kiểm tra xem người dùng đã đăng nhập hay chưa. Nếu đã đăng nhập thì đồng ý, còn nếu chưa đăng nhập thì chuyển đến trang Login.

Bước 1: Tạo mới 1 Base Controller

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using BanHangOnline.Common;

namespace BanHangOnline.Areas.Admin.Controllers

{

public class BaseController : Controller

{

protected override void OnActionExecuting(ActionExecutingContext filterContext)

{

var session = (UserLogin)Session[CommonConstants.USER_SESSION];

if(session==null)

{

filterContext.Result = new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary(new { Controller = "Login", action = "Index", Areas = "Admin" }));

}

base.OnActionExecuting(filterContext);

}

}

}

Bước 2: Vào trang HomeController

Thay thế kế thừa từ Controller sang thành BaseController.

Bước 3: Chạy chương trình.

Vào bất cứ trang nào, chương trình sẽ tự động URL về trang Login.

BÀI 6: INSERT DỮ LIỆU

1. Insert dữ liệu vào bảng User

Bước 1: tạo UserController.cs

Bước 2: Add View (Create) cho User

Trong UserDao viết thêm phương thức

public long Insert(User entity)

{

db.User.Add(entity);

db.SaveChanges();

return entity.ID;

}

Bước 3: Trong UserController viết

// POST: Admin/User/Create

[HttpPost]

public ActionResult Create(User user)

{

if (ModelState.IsValid)

{

var dao = new UserDao();

long id = dao.Insert(user);

if (id > 0)

{

return RedirectToAction("Index", "User");

}

else

{

ModelState.AddModelError("", "Thêm user không thành công.");

}

}

return View("Create");

}

Bước 4: Về trang Create.cshtml

Sửa lại dòng:

@using (Html.BeginForm("Create","User",FormMethod.Post))

Bước 5: Thêm mới 1 trang Index của User.

Bước 6: Chạy chương trình.

Hiện tại chương trình đã chèn được người dùng vào CSDL.

Nhưng còn một số vấn đề như sau:

  • Mã hóa Password sang Md5.

  • Nếu người dùng chưa nhập dữ liệu phải thông báo yêu cầu nhập đầy đủ thông tin. (Validate data)

  • Xử lý giao diện tạo người dùng theo mẫu.

  • Xử lý khi thêm mới trùng tên UserName.

+ Mã hóa Password sang Md5.

Mở UserController.cs thêm dòng lệnh:

var MhMd5 = MaHoaMd5.MD5Hash(user.Password);

user.Password = MhMd5;

+ Nếu người dùng chưa nhập dữ liệu phải thông báo yêu cầu nhập đầy đủ thông tin. (Validate data)

Mở EF\User sửa lại như sau:

Chạy chương trình:

+ Xử lý giao diện tạo người dùng theo mẫu.

Vì ở trang này là thêm User cho phần quản trị. Vì vậy ta chỉ cần lấy các thông tin

Username, Password, Name, Address, Email, Phone, Status.

Mở Create.cshtm chỉnh sửa lại code như sau:

@model KetNoiCSDL.EF.User

@{

ViewBag.Title = "Create";

Layout = "~/Areas/Admin/Views/Shared/_Layout.cshtml";

}

<h2>Tạo danh sách người dùng</h2>

@using (Html.BeginForm("Create", "User", FormMethod.Post))

{

@Html.AntiForgeryToken()

<div class="row">

<div class="col-lg-12">

<div class="panel panel-default">

<div class="panel-heading">

Mời bạn nhập đầy đủ các thông tin <br />

@Html.ValidationMessage("ThongBao")

</div>

<div class="panel-div">

<div class="row">

<div class="col-lg-6">

<form role="form">

<div class="form-group">

<div class="col-md-10">

@Html.LabelFor(model => model.UserName)

@Html.EditorFor(model => model.UserName, new { htmlAttributes = new { @class = "form-control" } })

@Html.ValidationMessageFor(model => model.UserName, "", new { @class = "text-danger" })

</div>

</div>

<div class="form-group">

<div class="col-md-10">

@Html.LabelFor(model => model.Password)

@Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })

@Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })

</div>

</div>

<div class="form-group">

<div class="col-md-10">

@Html.LabelFor(model => model.Name)

@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })

@Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })

</div>

</div>

<div class="form-group">

<div class="col-md-10">

@Html.LabelFor(model => model.Address)

@Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })

@Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })

</div>

</div>

<div class="form-group">

<div class="col-md-10">

@Html.LabelFor(model => model.Email)

@Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })

@Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })

</div>

</div>

<div class="form-group">

<div class="col-md-10">

@Html.LabelFor(model => model.Phone)

@Html.EditorFor(model => model.Phone, new { htmlAttributes = new { @class = "form-control" } })

@Html.ValidationMessageFor(model => model.Phone, "", new { @class = "text-danger" })

</div>

</div>

<div class="form-group">

<div class="col-md-10">

@Html.LabelFor(model => model.Status)

@Html.CheckBoxFor(model => model.Status, new { htmlAttributes = new { @class = "form-control" } })

@Html.ValidationMessageFor(model => model.Status, "", new { @class = "text-danger" })

</div>

</div>

</form>

<div class="form-group">

<div class="col-md-offset-2 col-md-10">

<input type="submit" value="Create" class="btn btn-primary" />

</div>

</div>

</div>

</div>

</div>

</div>

</div>

</div>

}

Chạy chương trình.

+ Xử lý khi thêm mới trùng UserName.

public ActionResult Create(User user)

{

if (ModelState.IsValid)

{

var dao = new UserDao();

var MhMd5 = MaHoaMd5.MD5Hash(user.Password);

user.Password = MhMd5;

var db = new BanhangOnlineDbContext();

if (db.User.Any(x=>x.UserName== user.UserName))

{

ModelState.AddModelError("ThongBao", "Tên đăng nhập này đã tồn tại");

}

else

{

long id = dao.Insert(user);

if (id > 0)

{

return RedirectToAction("Index", "User");

}

else

{

ModelState.AddModelError("", "Thêm user không thành công.");

}

}

}

return View("Create");

}

BÀI 7: HIỂN THỊ DANH SÁCH DỮ LIỆU VÀ PHÂN TRANG

Để phân trang danh sách dữ liệu chúng ta cần phải cài đặt thêm PagedList ở cả 2 Project:

Bước 1: Cài đặt PagedList

Bước 2: Trong UserDao viết thêm:

using PagedList;

public IEnumerable<User>ListAllPaging(int page,int pageSize)

{

return db.User.OrderByDescending(x=>x.CreatedDate).ToPagedList(page, pageSize);

}

Bước 3: Trong UserController viết như sau:

// GET: Admin/User

public ActionResult Index(int page=1,int pageSize=1)

{

var dao = new UserDao();

var model = dao.ListAllPaging(page, pageSize);

return View(model);

}

Bước 4: Sửa lại trong Index.cshtml:

@model PagedList.IPagedList<KetNoiCSDL.EF.User>

@using PagedList.Mvc;

@{

ViewBag.Title = "Index";

Layout = "~/Areas/Admin/Views/Shared/_Layout.cshtml";

}

<h2>Danh sách người dùng</h2>

<div class="row">

<div class="col-lg-12">

<div class="panel panel-default">

<div class="panel-heading">

Danh sách người dùng

</div>

<!-- /.panel-heading -->

<div class="panel-div">

<div class="table-responsive">

<table class="table table-striped table-bordered table-hover">

<thead>

<tr>

<th>#</th>

<th>Tài khoản</th>

<th>Tên</th>

<th>Email</th>

<th>Phone</th>

<th>Trạng thái</th>

</tr>

</thead>

<tdiv>

@foreach (var item in Model)

{

<tr>

<td>

<a href="User/Edit/@item.ID">Sửa</a>

<a href="User/Delete/@item.ID">Xóa</a>

</td>

<td>@item.UserName</td>

<td>@item.Name</td>

<td>@item.Email</td>

<td>@item.Phone</td>

<td>@item.Status</td>

</tr>

}

</tdiv>

</table>

@Html.PagedListPager(Model, page => Url.Action("Index", new { page }));

</div>

<!-- /.table-responsive -->

</div>

<!-- /.panel-div -->

</div>

<!-- /.panel -->

</div>

</div>

Bước 5: Chạy chương trình.

BÀI 8: UPDATE BẢN GHI TRONG CSDL

Bước 1: Mở UserDao.cs viết 2 phương thức sau:

public bool Update(User entity)

{

try

{

var user = db.User.Find(entity.ID);

user.Name = entity.Name;

if(!string.IsNullOrEmpty(entity.Password))

{

user.Password = entity.Password;

}

user.Name = entity.Name;

user.Address = entity.Address;

user.Email = entity.Email;

user.Phone = entity.Phone;

user.Status = entity.Status;

db.SaveChanges();

return true;

}

catch

{

return false;

}

}

public User ViewDetail(int id)

{

return db.User.Find(id);

}

Bước 2: Mở UserController.cs viết phương thức sau

public ActionResult Edit(int id)

{

var user = new UserDao().ViewDetail(id);

return View(user);

}

Bước 3: Tạo mới View Edit:

Copy toàn bộ code trong Create.cshtml dán vào Edit.cshtml rồi sửa lại như sau:

@model KetNoiCSDL.EF.User

@{

ViewBag.Title = "Edit";

Layout = "~/Areas/Admin/Views/Shared/_Layout.cshtml";

}

<h2>Cập nhật người dùng</h2>

@using (Html.BeginForm("Edit", "User", FormMethod.Post))

{

@Html.AntiForgeryToken()

<div class="row">

<div class="col-lg-12">

<div class="panel panel-default">

<div class="panel-heading">

Mời bạn nhập đầy đủ các thông tin

</div>

<div class="panel-div">

<div class="row">

<div class="col-lg-6">

<form role="form">

<div class="form-group">

<div class="col-md-10">

@Html.LabelFor(model => model.UserName)

@Html.EditorFor(model => model.UserName, new { htmlAttributes = new { @class = "form-control" } })

@Html.ValidationMessageFor(model => model.UserName, "", new { @class = "text-danger" })

</div>

</div>

<div class="form-group">

<div class="col-md-10">

@Html.LabelFor(model => model.Password)

@Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })

@Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })

</div>

</div>

<div class="form-group">

<div class="col-md-10">

@Html.LabelFor(model => model.Name)

@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })

@Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })

</div>

</div>

<div class="form-group">

<div class="col-md-10">

@Html.LabelFor(model => model.Address)

@Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })

@Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })

</div>

</div>

<div class="form-group">

<div class="col-md-10">

@Html.LabelFor(model => model.Email)

@Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })

@Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })

</div>

</div>

<div class="form-group">

<div class="col-md-10">

@Html.LabelFor(model => model.Phone)

@Html.EditorFor(model => model.Phone, new { htmlAttributes = new { @class = "form-control" } })

@Html.ValidationMessageFor(model => model.Phone, "", new { @class = "text-danger" })

</div>

</div>

<div class="form-group">

<div class="col-md-10">

@Html.LabelFor(model => model.Status)

@Html.CheckBoxFor(model => model.Status, new { htmlAttributes = new { @class = "form-control" } })

@Html.ValidationMessageFor(model => model.Status, "", new { @class = "text-danger" })

</div>

</div>

</form>

<div class="form-group">

<div class="col-md-offset-2 col-md-10">

<input type="submit" value="Cập nhật" class="btn btn-primary" />

</div>

</div>

</div>

</div>

</div>

</div>

</div>

</div>

}

Bước 4: Mở UserController.cs viết thêm phương thức:

// POST: Admin/User/Edit/5

[HttpPost]

public ActionResult Edit(User user)

{

if (ModelState.IsValid)

{

var dao = new UserDao();

if (!string.IsNullOrEmpty(user.Password))

{

var MhMd5 = MaHoaMd5.MD5Hash(user.Password);

user.Password = MhMd5;

}

var res = dao.Update(user);

if (res)

{

return RedirectToAction("Index", "User");

}

else

{

ModelState.AddModelError("", "Cập nhật không thành công.");

}

}

return View("Index");

}

Bước 5: Chạy chương trình.

Kích vào Sửa

BÀI 9: SỬ DỤNG AJAX ĐỂ XÓA BẢN GHI TRONG CSDL

Bước 1: Cài đặt Microsoft.jQuery.Unobtrusive.Ajax.

Phải chuột lên BanhangOnline ManageNuGetPackages..

Vào ToolNuGet Package Manager Package Manager Console

Qua google tìm lệnh như sau, rồi copy

Dán vào cửa sổ Console. Enter

Install-Package Microsoft.jQuery.Unobtrusive.Ajax -Version 3.2.3

Sau khi cài đặt thành công:

Bước 2: Thêm Ajax vừa cài vào trang _Layout.

Mở trang _Layout.cshtm

Mở thư viện scripts.

Kéo file jquery.unobtrusive-ajax.js thả vào trong _Layout tại vị trí như sau:

Bước 3: Mở UserDao.cs viết thêm phương thức Delete:

public bool Delete(int id)

{

try

{

var user = db.User.Find(id);

db.User.Remove(user);

db.SaveChanges();

return true;

}

catch(Exception)

{

return false;

}

}

Bước 4: Mở UserController.cs viết thêm phương thức:

[HttpDelete]

public ActionResult Delete(int id)

{

var user = new UserDao().Delete(id);

return RedirectToAction("Index");

}

Bước 5: Mở trang Index tại vị trí sau:

Xóa dòng lệnh này và thay thế bằng Ajax:

@Ajax.ActionLink("Xóa","Delete",new { @id = item.ID },new AjaxOptions

{

Confirm="Bạn có muốn xóa người dùng này?",

OnComplete="$('#row_"+item.ID+"').remove()",

HttpMethod="Delete"

})

Sau khi thay thế:

Bước 6: Chạy chương trình:

BÀI 10: TẠO CHỨC NĂNG TÌM KIẾM DỮ LIỆU

Bước 1: Mở UserDao.cs sửa phương thức ListAllPaging:

public IEnumerable<User> ListAllPaging(string searchString,int page, int pageSize)

{

IQueryable<User> model= db.User;

if (!string.IsNullOrEmpty(searchString))

{

model = model.Where(x => x.UserName.Contains(searchString) || x.Name.Contains(searchString));

}

return model.OrderByDescending(x => x.CreatedDate).ToPagedList(page, pageSize);

}

Bước 2: Mở UserController.cs sửa lại phương thức:

// GET: Admin/User

public ActionResult Index(string searchString,int page = 1, int pageSize = 3)

{

var dao = new UserDao();

var model = dao.ListAllPaging(searchString,page, pageSize);

return View(model);

}

Bước 3: Vào trang Index, sửa lại như sau:

@using (Html.BeginForm("Index", "User", FormMethod.Get))

{

<div class="row">

<div class="col-lg-12">

<div class="col-md-offset-0">

<input type="text" name="searchString" />

<input type="submit" value="Tìm kiếm" class="btn btn-primary" />

</div>

</div>

</div>

}

Bước 4: Chạy chương trình

Phần tìm kiếm cần chỉnh sửa sao cho:

+ Sau khi tìm kiếm, ô tìm kiếm không bị mất thông tin cần tìm.

+ Nếu tìm thấy nhiều kết quả thì hiển thị phân trang.

Bước 1: Mở UserController.cs thêm dòng lệnh:

ViewBag.ChuoiTimKiem = searchString;

Bước 2: Mở trang Index.cshtml thêm lệnh: value="@ViewBag.ChuoiTimKiem" như sau:

<input type="text" value="@ViewBag.ChuoiTimKiem" name="searchString" />

Bước 3: Ở trang Index.cshtml chỗ phân trang thêm lệnh:

,@searchString= ViewBag.ChuoiTimKiem như sau:

@Html.PagedListPager(Model, page => Url.Action("Index", new { page,@searchString= ViewBag.ChuoiTimKiem }));

BÀI 11: TÍCH HỢP CKFINDER ĐỂ QUẢN LÝ THƯ VIỆN ẢNH ONLINE

Bước 1: Download CKFinder, giải nén chúng ta được.

Sau khi giải nén chúng ta xóa 2 thư mục đầu tiên

Bước 2: Trong BanhangOnline. Tạo thư mục Plugins

Bước 3: Sao chép thư mục Ckfinder vừa giải nén ở bước 1 dán vào thư mục Plugins này:

Đồng thời Include in Project (Để hiển thị các file nên chọn show all file) ở trên

Bước 4: Mở _Layout.cshtm kéo và thả file ckfinder.js vào đúng vị trí sau:

Bước 5: Tạo mới 1 ContentController:

Bước 6: Tạo mới 1 Create View

Tìm đến trường Image

Sửa lại như sau:

<div class="form-group">

@Html.LabelFor(model => model.Image, htmlAttributes: new { @class = "control-label col-md-2" })

<div class="col-md-10">

@Html.TextBoxFor(model => model.Image, new { htmlAttributes = new { @class = "form-control"},@id="txtImage" })

<a id="SelectImage">Chọn ảnh</a>

@Html.ValidationMessageFor(model => model.Image, "", new { @class = "text-danger" })

</div>

</div>

Bước 7: Add thêm file CkFinder.dll vào References

Chọn nút Browse chọn đường dẫn:

\BanHangOnline\BanHangOnline\Assets\Admin\js\Plugins\ckfinder\bin\Release

Bước 8: Mở _Layout.cshtml thêm dòng lệnh

@RenderSection("jsFooter",required:false)

Bước 9: Vào trang Create.cshtml

@section jsFooter{

<script>

$('#SelectImage').on('click', function (e) {

e.preventDefault();

var finder=new CKFinder();

finder.selectActionFunction=function(url){

$('#txtImage').val(url);

};

finder.popup();

})

</script>

}

Bước 10: Mở file Config.ascx

- Đổi return false; thành return true;

LicenseName = "@tuannguyen";

LicenseKey = "AUKPSE6XSVSJTP4MSV9RQKJBKGLL3KN7";

BaseUrl = "/Anh";

Bước 11: Tạo thư mục Anh:

Bước 12: Chạy chương trình

BÀI 12 TÍCH HỢP TRÌNH SOẠN THẢO CKEDITOR.

Bước 1: Tải ckeditor. Vào ckeditor/download chọn Full Package.

Giải nén ra ta được thư mục ckeditor

Bước 2: Sao chép thư mục ckeditor vào thư mục Plugins trong BanhangOnline.

Sau đó Include project:

Bước 3: Nhúng Ckeditor.js vào file _Layout.cshtml tại vị trí sau ckfinder.js

Bước 4: Vào trang Config.js viết:

CKEDITOR.editorConfig = function( config ) {

// Define changes to default configuration here. For example:

// config.language = 'fr';

// config.uiColor = '#AADC6E';

config.syntaxhightlight_lang = 'cshap';

config.syntaxhightlight_hideControls = true;

config.language = 'vi';

config.filebrowserBrowseUrl = '/Assets/Admin/js/Plugins/ckfinder/ckfinder.html';

config.filebrowserImageBrowseUrl = '/Assets/Admin/js/Plugins/ckfinder.html?Type=Images';

config.filebrowserFlashBrowseUrl = '/Assets/Admin/js/Plugins/ckfinder.html?Type=Flash';

config.filebrowserUploadUrl = '/Assets/Admin/js/Plugins/ckfinder/core/connector/aspx/connector.aspx? command=QuickUpload&Type=File';

config.filebrowserImageUploadUrl = '/Anh';

config.filebrowserFlashUploadUrl = '/Assets/Admin/js/Plugins/ckfinder/core/connector/aspx/connector.aspx? command=QuickUpload&Type=Flash';

CKFinder.setupCKEditor(null, '/Assets/Admin/js/Plugins/ckfinder');

};

Bước 5: Mở trang Create của Content, tìm đến trường detail sửa lại như sau:

<div class="form-group">

@Html.LabelFor(model => model.Detail, htmlAttributes: new { @class = "control-label col-md-2" })

<div class="col-md-10">

@Html.TextAreaFor(model => model.Detail, new { htmlAttributes = new { @class = "form-control" },@id="txtContent" })

@Html.ValidationMessageFor(model => model.Detail, "", new { @class = "text-danger" })

</div>

</div>

Đồng thời viết thêm:

var editor = CKEDITOR.replace('txtContent', {

customConfig: '/Assets/Admin/js/Plugins/ckeditor/config.js',

});

Bước 6: Build và chạy chương trình.

Bài tập làm thêm:

- Insert được Content vào trong CSDL

Chú ý: CKEDITOR viết thêm htmlEncodeOutput: true

var editor = CKEDITOR.replace('txtContent', {htmlEncodeOutput: true ,

customConfig: '/Assets/Admin/js/Plugins/ckeditor/config.js',

});

BÀI 13: SỬ DỤNG DROPDOWNLIST.

Mở bảng Category và nhập dữ liệu như sau:

Bước 1: Tạo CategoryDao.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using KetNoiCSDL.EF;

namespace KetNoiCSDL.DAO

{

public class CategoryDao

{

BanhangOnlineDbContext db = null;

public CategoryDao()

{

db = new BanhangOnlineDbContext();

}

public List<Category> ListAll()

{

return db.Category.Where(x => x.Status == true).ToList();

}

}

}

Bước 2: Vào ContentController.cs viết code:

// GET: Admin/Content/Create

public ActionResult Create()

{

SetViewBag();

return View();

}

public void SetViewBag(long? selectedID=null)

{

var dao = new CategoryDao();

ViewBag.CategoryID = new SelectList(dao.ListAll(), "ID", "Name", selectedID);

}

Bước 3: Về view Create

Tìm đến CategoryID sửa lại dòng:

@Html.DropDownListFor(model => model.CategoryID,null, new { htmlAttributes = new { @class = "form-control" } })

Bước 4: chạy chương trình

Để sử dụng Dropdownlist vào việc Create, Edit chúng ta cần làm như sau

+ Create:

Bước 1: Viết HttpGet và HttpPost cho phương thức Create như sau:

[HttpGet]

public ActionResult Create()

{

SetViewBag();

return View();

}

[HttpPost]

public ActionResult Create(Content model)

{

if(ModelState.IsValid)

{

//Lệnh thêm vào CSDL ở đây.

}

SetViewBag();

return View();

}

Bước 2: Tạo mới ContentDao.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using KetNoiCSDL.EF;

{

public class ContentDao

{

BanhangOnlineDbContext db = null;

public ContentDao()

{

db = new BanhangOnlineDbContext ();

}

public Content GetByID(long id)

{

return db.Content.Find(id);

}

}

}

+ Edit :

Viết phương thức Edit cho HttpGet và HttpPost như sau:

// GET: Admin/Content/Edit/5

[HttpGet]

public ActionResult Edit(long id)

{

var dao = new ContentDao();

var content = dao.GetByID(id);

SetViewBag(content.CategoryID);

return View();

}

// POST: Admin/Content/Edit/5

[HttpPost]

public ActionResult Edit(Content model)

{

if(ModelState.IsValid)

{

//Lệnh sửa viết ở đây.

}

SetViewBag(model.CategoryID);

return View();

}

BÀI 14 TẠO THÔNG BÁO CHO NGƯỜI DÙNG VỚI BOOTSTRAP STYLE

Bước 1: Mở BaseController.cs Viết phương thức sau:

protected void SetAlert(string message, string type)

{

TempData["AlertMessage"] = message;

if (type == "success")

{

TempData["AlertType"] = "alert-success";

}

else if (type == "warning")

{

TempData["AlertType"] = "alert-warning";

}

else if (type == "error")

{

TempData["AlertType"] = "alert-danger";

}

}

Bước 2: Tạo 1 file Alert.js và viết Code như sau:

$(function () {

$('#AlertBox').removeClass('hide');

$('#AlertBox').delay(1000).slideUp(500);

});

Bước 3 : Nhúng file Alert.js vào trong _Layout.cshtml

<script src="/Assets/Admin/js/Alert.js"></script>

Bước 4: Áp dụng Alert. Mở UserController.

Trong phương thức Create, thông báo thành công hay thất bại.

SetAlert("Thêm User thành công", "success");

SetAlert("Tên đăng nhập này đã tồn tại", "error");

Bước 5: Mở _Layout.cshtml thêm đoạn code sau

@if (TempData["AlertMessage"] != null)

{

<div id="AlertBox" class="alert @TempData["AlertType"] hide">

@TempData["AlertMessage"]

</div>

}

Bước 6: Chạy chương trình.

BÀI 15 TẠO TRANG CHỦ CHO NGƯỜI DÙNG.

Bước 1: Bạn truy cập vào trang https://w3layouts.com.

Tìm kiếm Home shoppe

Download và giải nén.

Bước 2: Copy các thư mục sau và đưa vào Project trong thư mục Assets\Client

Copy hoàn thành:

Bước 3: Tạo mới 1 trang _Layout.cshtml trong thư mục View\Shared

Bước 4: Mở trang Index coypy toàn bộ code và dán vào trang _Layout.cshtml

Xóa những dòng này

Dán vào

Bước 5: Thay đổi đường dẫn cho các tài nguyên: /Assets/Client/

Bước 6: Tạo mới 1 trang Index (trang chủ) lấy layout là trang _Layout.cshtml vừa thiết lập.

Bước 7: Cắt đoạn code (thẻ main) trong _Layout dán qua trang Index:

Đồng thời tại vị trí vừa cắt ta thay bằng lệnh @RenderBody()

Bước 8: Cắt thẻ Slide đưa qua trang Index. (Sử dụng Section)

Bước 9: Chạy chương trình:

BÀI 16: LẤY DỮ LIỆU CHO CÁC THÀNH PHẦN DÙNG CHUNG

1. Lấy dữ liệu cho Menu chính

Bước 1: Nhập dữ liệu như sau:

Bước 2: Tạo mới MenuDao.cs

Viết phương thức ListByGroupID

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using KetNoiCSDL.EF;

namespace KetNoiCSDL.DAO

{

public class MenuDao

{

BanhangOnlineDbContext db = null;

public MenuDao()

{

db = new BanhangOnlineDbContext();

}

public List<Menu>ListByGroupID(int groupId)

{

return db.Menu.Where(x => x.TypeID ==groupId).ToList();

}

}

}

Bước 3: Viết phương thức MainMenu trong HomeController.

[ChildActionOnly]

public ActionResult MainMenu()

{

var model = new MenuDao().ListByGroupID(1);

return PartialView(model);

}

Bước 4: Tạo mới View MainMenu.cshtml

Chú ý chọn Create as a partial view

Bước 5: Thay đổi code tĩnh bằng code động.

Vào trang _Layout.cs tìm đến thẻ menu

Cắt thẻ này (Chỗ đánh dấu)

Dán vào MainMenu.cshtml vừa Add ở bước 4.

Viết lại code cho trang MainMenu.cshtml như sau:

@model List<KetNoiCSDL.EF.Menu>

<div class="menu">

<ul>

@foreach(var item in Model)

{

<li><a href="@item.Link" target="@item.Target">@item.Text</a></li>

}

<div class="clear"></div>

</ul>

</div>

Qua trang _Layout.cshtml tại vị trí đã cắt thẻ menu thay thế bằng câu lệnh:

@{Html.RenderAction("MainMenu","Home");}

2. Lấy dữ liệu cho Menu Top.

Bước 1: Tạo phương thức TopMenu trong HomeController.

[ChildActionOnly]

public ActionResult TopMenu()

{

var model = new MenuDao().ListByGroupID(2);

return PartialView(model);

}

Bước 2: Add mới view TopMenu.cshtml

Bước 3: Thay đổi Top Menu tĩnh bằng Top Menu động.

Mở _Layout.cshtml tìm đến thẻ call và cắt thẻ này

Dán qua TopMenu.cshtml

Sửa lại code:

@model List<KetNoiCSDL.EF.Menu>

<div class="call">

<p><span>Nếu bạn cần?</span> Xin hãy gọi <span class="number">0978-187-154</span></span></p>

</div>

<div class="account_desc">

<ul>

@foreach (var item in Model)

{

<li><a href="@item.Link" target="@item.Target">@item.Text</a></li>

}

</ul>

</div>

<div class="clear"></div>

Qua trang _Layout.cshtml viết lệnh sau tại vị trí đã cắt

@{Html.RenderAction("TopMenu", "Home");}

Chú ý:

- Nếu muốn Menu hiển thị theo thứ tự theo DisplayOrderby trong CSDL thì ở phương thức ListByGroupID trong UserDao ta sửa lại như sau:

public List<Menu>ListByGroupID(int groupId)

{

return db.Menu.Where(x => x.TypeID ==groupId).OrderBy(x=>x.DisplayOrder).ToList();

}

-Nếu muốn chỉ hiển thị những Menu có status =1

return db.Menu.Where(x => x.TypeID ==groupId && x.Status==true).OrderBy(x=>x.DisplayOrder).ToList();

3. Lấy dữ liệu cho Footer

Bước 1: Tạo FooterDao

using KetNoiCSDL.EF;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace KetNoiCSDL.DAO

{

public class FooterDao

{

DBContext db = null;

public FooterDao()

{

db = new DBContext();

}

public Footer LayFooter()

{

return db.Footer.SingleOrDefault();

}

}

}

Bước 2: Tạo phương thức trong HomeController.

[ChildActionOnly]

public ActionResult MenuFooter()

{

var model = new FooterDao().LayFooter();

return PartialView(model);

}

Bước 3: Tạo mới View MenuFooter.

Viết code:

@model KetNoiCSDL.EF.Footer

@Html.Raw(Model.Content)

Bước 4: Qua trang _Layout.cshtml thay đổi dữ liệu tĩnh sang động.

Tìm đến thẻ Footer, sau đó cắt thẻ wrap ở hình dưới

Thay thế bằng câu lệnh

@{Html.RenderAction("MenuFooter", "Home");}

Bước 5: Qua SQL Server. Dùng câu lệnh chèn đoạn code vừa cắt vào bảng Footer.

BÀI 17: LẤY DỮ LIỆU CHO TRANG CHỦ.

1. Lấy dữ liệu cho menu trái

Bước 1: Tao mới 1 CategoryDao.

Viết code cho phương thức ListAll

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using KetNoiCSDL.EF;

namespace KetNoiCSDL.DAO

{

public class CategoryDao

{

BanhangOnlineDbContext db = null;

public ProductCategoryDao()

{

db = new BanhangOnlineDbContext();

}

public List<Category> ListAll()

{

return db. Category.Where(x => x.Status == true).OrderBy(x => x.DisplayOrder).ToList();

}

}

}

Bước 2: Tạo mới phương thức Category trong HomeController.

[ChildActionOnly]

public ActionResult Category()

{

var model = new CategoryDao().ListAll();

return PartialView(model);

}

Bước 3: Thêm mới view Category

Bước 4: Thay đổi code để chuyển từ dữ liệu tĩnh sang động.

Vào Index.cshtml tìm đến thẻ categories. Cắt thẻ này và dán vào Category.cshtml

Sửa lại code cho Category.cshtml

@model List<KetNoiCSDL.EF.Category>

<div class="categories">

<ul>

<h3>Danh mục sản phẩm</h3>

@foreach (var item in Model)

{

<li><a href="/san-pham/@item.MetaTitle">@item.Name</a></li>

}

</ul>

</div>

Về trang Index.cshtml tại vị trí vừa cắt thay thế bằng đoạn code:

@{ Html.RenderAction("Category", "Home");}

2. Lấy dữ liệu cho Slide (Sử dụng ViewBag)

Các bạn có thể dùng như cách trên để binding dữ liệu hoặc có thể dùng ViewBag như sau

Bước 1: Tạo mới SlideDao

Viết code cho SlideDao

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using KetNoiCSDL.EF;

namespace KetNoiCSDL.DAO

{

public class SlideDao

{

BanhangOnlineDbContext db = null;

public SlideDao()

{

db = new BanhangOnlineDbContext();

}

public List<Slide> ListAll()

{

return db.Slide.Where(x => x.Status == true).OrderBy(y => y.DisplayOrder).ToList();

}

}

}

Bước 2: Vào HomeController Viết code:

public ActionResult Index()

{

ViewBag.TuiSlide = new SlideDao().ListAll();

return View();

}

Bước 3: Vào trang Index, sửa lại để lấy dữ liệu động

Viết câu lệnh: Khai báo sử dụng ViewBag

var sli = (List<KetNoiCSDL.EF.Slide>)ViewBag.TuiSlide;

Tìm đến thẻ mover như hình dưới

Sử dụng lệnh @Foreach như hình dưới

Chuyển đoạn code được đánh dấu vào trong khối lệnh @Foreach

Xóa 2 thẻ được đánh dấu như hình dưới

Sửa lại code cho vòng lặp @Foreach

3. Lấy dữ liệu cho các sản phẩm

Nhập dữ liệu:

Trong sản phẩm có 2 danh sách: Sản phẩm mới và Sản phẩm bán chạy

- Sản phẩm mới.

Bước 1: Tạo ProductDao.cs

Viết code

public class ProductDao

{

DBContext db = null;

public ProductDao()

{

db = new DBContext();

}

}

public List<Product>NewProList(int numpro)

{

return db.Product.Where(x => x.Status == true).OrderByDescending(x => x.CreatedDate).Take(numpro).ToList();

}

Bước 2: Vào HomeController viết code sử dụng ViewBag

ViewBag.TuiNewPro = new ProductDao().NewProList(4);

Bước 3: Vào trang Index, sửa lại để lấy dữ liệu động

Khai báo sử dụng ViewBag

var newpro = (List<KetNoiCSDL.EF.Product>)ViewBag.TuiNewPro;

Tìm đến thẻ section group có 4 sản phẩm như hình dưới

Sử dụng lệnh lặp foreach, cắt 1 dòng đưa vào khối lặp. Xóa 3 dòng dưới

Chỉnh sửa code:

- Sản phẩm bán chạy

Bước 1: Mở ProductDao.cs viêt phương thức sau:

public List<Product>FeatureProList(int numpro)

{

return db.Product.Where(x => x.Status == true).OrderByDescending(x => x.ViewCount).Take(numpro).ToList();

}

Bước 2: Vào HomeController. Viết code sử dụng ViewBag:

ViewBag.TuiFeaturePro = new ProductDao().FeatureProList(4);

Bước 3: Vào trang Index sửa lại như sau:

BÀI 18: CÁCH TẠO URL THÂN THIỆN CHO SEO

1. Tạo URL cho Danh mục sản phẩm ProductCategory. (Lấy nhiều sản phẩm)

Bước 1: Mở View Category.cshtml sửa lại như sau:

@model List<KetNoiCSDL.EF.Category>

<div class="categories">

<ul>

<h3>Danh mục sản phẩm</h3>

@foreach (var item in Model)

{

<li><a href="san-pham/@item.MetaTitle-@item.ID">@item.Name</a></li>

}

</ul>

</div>

Bước 2: Mở ProductCategoryDao. Viết phương thức

public List<ProductCategory>DStheoID(long id)

{

return db.ProductCategory.Where(x => x.ParentID == id).ToList();

}

Bước 3: Tạo mới ProductCategoryController. Viết phương thức

public ActionResult DanhMucSP(long id)

{

ViewBag.DmSp = new ProductCategoryDao().DStheoID(id);

return View();

}

Bước 4: Add View

Viết code cho View:

@{

ViewBag.Title = "Danh mục";

Layout = "~/Views/Shared/_Layout.cshtml";

var dmsp = (List<KetNoiCSDL.EF.ProductCategory>)ViewBag.DmSp;

}

<h1>Danh mục sản phẩm</h1>

<a>-----------------------</a>

@foreach (var item in dmsp)

{

<h3>@item.Name</h3>

<a>-----------------------</a>

}

Bước 5: Mở RouterConfig.cs

Viết thêm đoạn code sau:

routes.MapRoute(

name: "Category",

url: "san-pham/{outputpre}-{id}",

defaults: new { controller = "ProductCategory", action = "DanhMucSP", id = UrlParameter.Optional },

namespaces: new[] { "BanHangOnline.Controllers" }

);

Bước 6: Chạy chương trình:

Kích vào Tivi

2. Tạo URL cho chi tiết sản phẩm Product. (Lấy 1 sản phẩm)

Bước 1: Vào ProductDao.cs viết phương thức sau:

public Product LaySP(long id)

{

return db.Product.Find(id);

}

Bước 2: Vào ProductController.cs viết phương thức:

public ActionResult ChiTietSP(long id)

{

ViewBag.ctsp = new ProductDao().LaySP(id);

return View();

}

Bước 3: Tạo mới View ChiTietSP

@{

ViewBag.Title = "ChiTietSP";

Layout = "~/Views/Shared/_Layout.cshtml";

var CTSP = (KetNoiCSDL.EF.Product)ViewBag.ctsp;

}

<h1>Chi tiết sản phẩm</h1>

<a>------------------------</a>

@{ var item = CTSP;}

<h3>@item.Name</h3>

<h3>@item.Price</h3>

Bước 4: Vào RouterConfig.cs viết code:

routes.MapRoute(

name: "Product",

url: "chi-tiet/-{id}",

defaults: new { controller = "Product", action = "ChiTietSP", id = UrlParameter.Optional },

namespaces: new[] { "BanHangOnline.Controllers" }

);

Bước 5: Chạy chương trình:

Kích vào sản phẩm bất kỳ.

3. Tạo URL cho những trang không có tham số (ví dụ như trang Giới thiệu,…)

Bước 1: Tạo AboutController.cs

Bước 2: Add View

Bước 3: Vào RouterConfig khai báo:

routes.MapRoute(

name: "Gioi thieu",

url: "gioi-thieu",

defaults: new { controller = "About", action = "index", id = UrlParameter.Optional },

namespaces: new[] { "BanHangOnline.Controllers" }

Bước 4: Chạy chương trình.

Tương tự như vậy các em tạo các liên kết cho trang Giao hàng

BÀI 19: TẠO LIÊN HỆ (INSERT CSDL)

Bước 1: Tạo ContactDao.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using KetNoiCSDL.EF;

namespace KetNoiCSDL.DAO

{

public class ContactDao

{

BanhangOnlineDbContext db = null;

public ContactDao()

{

db = new BanhangOnlineDbContext();

}

public long Insert(Contact entity)

{

db.Contact.Add(entity);

db.SaveChanges();

return entity.ID;

}

}

}

Bước 2: Tạo ContactController.

using KetNoiCSDL.DAO;

using KetNoiCSDL.EF;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

namespace BanHangOnline.Controllers

{

public class ContactController : Controller

{

// GET: Contact

public ActionResult Index()

{

return View();

}

protected void SetAlert(string message, string type)

{

TempData["AlertMessage"] = message;

if (type == "success")

{

TempData["AlertType"] = "alert-success";

}

else if (type == "warning")

{

TempData["AlertType"] = "alert-warning";

}

else if (type == "error")

{

TempData["AlertType"] = "alert-danger";

}

}

[HttpPost]

public ActionResult Create(Contact contact)

{

if (ModelState.IsValid)

{

var dao = new ContactDao();

long id = dao.Insert(contact);

if (id > 0)

{

SetAlert("Gửi đi thành công", "success");

}

else

{

SetAlert("Chưa được gửi", "error");

}

}

return View("Index");

}

}

}

Bước 3: Add thêm View

Viết code cho View

@model KetNoiCSDL.EF.Contact

@{

ViewBag.Title = "Index";

Layout = "~/Views/Shared/_Layout.cshtml";

}

<script src="~/Assets/Admin/js/Alert.js"></script>

@using (Html.BeginForm("Create", "Contact", FormMethod.Post))

{

@Html.AntiForgeryToken()

<div class="main">

<div class="content">

<div class="section group">

<div class="col span_2_of_3">

<div class="contact-form">

<div id="status_view">

@if (TempData["AlertMessage"] != null)

{

<div id="AlertBox" class="alert @TempData["AlertType"] hide">

@TempData["AlertMessage"]

</div>

}

</div>

<h2>Xin để lại thông tin</h2>

<form role="form">

<div>

@Html.LabelFor(model => model.Name)

@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })

@Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })

</div>

<div>

@Html.LabelFor(model => model.Mobi)

@Html.EditorFor(model => model.Mobi, new { htmlAttributes = new { @class = "form-control" } })

@Html.ValidationMessageFor(model => model.Mobi, "", new { @class = "text-danger" })

</div>

<div>

@Html.LabelFor(model => model.Email)

@Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })

@Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })

</div>

<div>

@Html.LabelFor(model => model.subject)

@Html.EditorFor(model => model.subject, new { htmlAttributes = new { @class = "form-control" } })

@Html.ValidationMessageFor(model => model.subject, "", new { @class = "text-danger" })

</div>

<div>

<span><input type="submit" value="Gửi" class="myButton"></span>

</div>

</form>

</div>

</div>

<div class="col span_1_of_3">

<div class="contact_info">

<h3>Tìm địa chỉ Công ty</h3>

<div class="map">

<iframe width="100%" height="175" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="https://maps.google.co.in/maps?f=q&amp;source=s_q&amp;hl=en&amp;geocode=&amp;q=Lighthouse+Point,+FL,+United+States&amp;aq=4&amp;oq=light&amp;sll=26.275636,-80.087265&amp;sspn=0.04941,0.104628&amp;ie=UTF8&amp;hq=&amp;hnear=Lighthouse+Point,+Broward,+Florida,+United+States&amp;t=m&amp;z=14&amp;ll=26.275636,-80.087265&amp;output=embed"></iframe><br><small><a href="https://maps.google.co.in/maps?f=q&amp;source=embed&amp;hl=en&amp;geocode=&amp;q=Lighthouse+Point,+FL,+United+States&amp;aq=4&amp;oq=light&amp;sll=26.275636,-80.087265&amp;sspn=0.04941,0.104628&amp;ie=UTF8&amp;hq=&amp;hnear=Lighthouse+Point,+Broward,+Florida,+United+States&amp;t=m&amp;z=14&amp;ll=26.275636,-80.087265" style="color:#666;text-align:left;font-size:12px">View Larger Map</a></small>

</div>

</div>

<div class="company_address">

<h3>Company Information :</h3>

<p>500 Lorem Ipsum Dolor Sit,</p>

<p>22-56-2-9 Sit Amet, Lorem,</p>

<p>USA</p>

<p>Phone:(00) 222 666 444</p>

<p>Fax: (000) 000 00 00 0</p>

<p>Email: <span>[email protected]</span></p>

<p>Follow on: <span>Facebook</span>, <span>Twitter</span></p>

</div>

</div>

</div>

</div>

</div>

}

Mẫu view khi chạy

Bước 4: Tạo Link Liên hệ ở trang chủ

Vào RouterConfig.cs viết lệnh như sau :

routes.MapRoute(

name: "LienHe",

url: "lien-he",

defaults: new { controller = "Contact", action = "Index", id = UrlParameter.Optional },

namespaces: new[] { "BHOnline.Controllers" }

);

BÀI 20: TẠO TRANG TIN TỨC

Mẫu trang tin tức như sau:

Khi kích vào Chi tiết.

Thiết kế bảng News:

Nhập dữ liệu cho bảng New khoảng 3 đến 5 bản ghi.

Bước 1: Tạo NewsDao.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using KetNoiCSDL.EF;

using PagedList;

namespace KetNoiCSDL.DAO

{

public class NewsDao

{

BanhangOnlineDbContext db = null;

public NewsDao()

{

db = new BanhangOnlineDbContext();

}

//Phân trang

public IEnumerable<News> ListAllPage(int page, int pageSize)

{

return db.News.OrderByDescending(x => x.CreatedDate).ToPagedList(page, pageSize);

}

//Đọc từng bản tin khi người dùng kích vào Chi tiết

public News ReadNew(long id)

{

return db.News.Where(x => x.ID == id).SingleOrDefault();

}

}

}

Bước 2: Tạo NewsController.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using KetNoiCSDL.DAO;

namespace BanHangOnline.Controllers

{

public class NewsController : Controller

{

//Phân trang

public ActionResult Index(int page=1, int pageSize = 2)

{

var dao = new NewsDao();

var model = dao.ListAllPage(page, pageSize);

return View(model);

}

//Đọc tin chi tiết

public ActionResult Detail(long id)

{

ViewBag.detail = new NewsDao().ReadNew(id);

return View();

}

}

}

Bước 3: Tạo View cho trang Tin-Tức:

@model PagedList.IPagedList<KetNoiCSDL.EF.News>

@using PagedList.Mvc;

@{

ViewBag.Title = "Index";

Layout = "~/Views/Shared/_LayoutNoFoot.cshtml";

}

<div class="main">

<div class="content">

@foreach (var item in Model)

{

var url = "/tin-tuc/-" + item.ID;

<div class="image group">

<div class="grid images_3_of_1">

<amp-img src="@item.Image" alt="@item.Title" />

</div>

<div class="grid news_desc">

<h3>@item.Title </h3>

<h4>Đăng bài ngày @item.CreatedDate.ToString() by <span><a href="#">@item.ModifiedBy</a></span></h4>

<p>@item.Description</p>

<p><a href="@url" pre="Xem chi tiết">[Chi tiết]</a></p>

</div>

</div>

}

</div>

<div class="content-pagenation">

<li class="active">@Html.PagedListPager(Model, page => Url.Action("Index", new { page }));</li>

<div class="clear"> </div>

</div>

</div>

Bước 4: Tạo view cho trang Tin tức chi tiết: (Detail)

Về NewsController.cs

Viết code cho view

@{

ViewBag.Title = "Detail";

Layout = "~/Views/Shared/_Layout.cshtml";

var news = (List<KetNoiCSDL.EF.News>)ViewBag.news;

var tin = (KetNoiCSDL.EF.News)ViewBag.detail;

}

<div class="main">

<div class="content">

<div class="image group">

<div class="grid images_3_of_1">

<amp-img src="@tin.Image" alt="@tin.Title" />

</div>

<div class="grid news_desc">

<h3>@tin.Title </h3>

<h4>Đăng bài lúc @tin.CreatedDate.ToString() bởi <span><a href="#">@tin.Name</a></span></h4>

<p>@tin.Description</p>

<p>@tin.Detail</p>

</div>

</div>

</div>

</div>

Bước 5: Mở RouteConfig.cs viết thêm:

routes.MapRoute(

name: "News",

url: "tin-tuc",

defaults: new { controller = "News", action = "Index", id = UrlParameter.Optional },

namespaces: new[] { "BHOnline.Controllers" }

);

routes.MapRoute(

name: "NewsDetail",

url: "tin-tuc/-{id}",

defaults: new { controller = "News", action = "Detail", id = UrlParameter.Optional },

namespaces: new[] { "BHOnline.Controllers" }

BÀI 21 CÁCH GỬI EMAIL TRONG ASP.NET MVC

Bước 1: Khai báo trong file web.config như sau:

<add key="FromEmailAddress" value="[email protected]" />

<add key="FromEmailDisplayName" value="Đóng góp ý kiến" />

<add key="FromEmailPassword" value="abcd$1234" />

<add key="SMTPHost" value="smtp.gmail.com" />

<add key="SMTPPort" value="587" />

<add key="EnabledSSL" value="true" />

<add key="ToEmailAddress" value="[email protected]" />

Bước 2: Xây dựng class MailHelper.cs

Tạo mới class MailHelper.cs trong thư mục Common như sau:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net.Mail;

using System.Text;

using System.Threading.Tasks;

using System.Configuration;

using System.Net;

namespace BanHangOnline

{

public class MailHelper

{

public void SendMail(string toEmailAddress, string subject,string content)

{

var fromEmailAddress = ConfigurationManager.AppSettings["FromEmailAddress"].ToString();

var fromEmailDisplayName = ConfigurationManager.AppSettings["FromEmailDisplayName"].ToString();

var fromEmailPassword = ConfigurationManager.AppSettings["FromEmailPassword"].ToString();

var smtpHost = ConfigurationManager.AppSettings["SMTPHost"].ToString();

var smtpPort = ConfigurationManager.AppSettings["SMTPPort"].ToString();

bool enabledSsl = bool.Parse(ConfigurationManager.AppSettings["EnabledSSL"].ToString());

string div = content;

MailMessage message = new MailMessage(new MailAddress(fromEmailAddress, fromEmailDisplayName), new MailAddress(toEmailAddress));

message.Subject = subject;

message.IsBodyHtml = true;

message.Body = div;

var client = new SmtpClient();

client.Credentials = new NetworkCredential(fromEmailAddress, fromEmailPassword);

client.Host = smtpHost;

client.EnableSsl = enabledSsl;

client.Port = !string.IsNullOrEmpty(smtpPort) ? Convert.ToInt32(smtpPort) : 0;

client.Send(message);

}

}

}

Chú ý để sử dụng được using System.Configuration; ta cần phải Add References

Bước 3: Tạo mới file GopY.html trong thư mục Assets/Client/Temp/GoyY.html

<!DOCTYPE html>

<html>

<head>

<pre> Khách hàng đóng góp ý kiến: {{CustomerName}}</pre>

<output charset="utf-8" />

</head>

<div>

Thông tin về khách hàng đóng góp ý kiến: {{CustomerName}}

Điện thoại: {{Phone}} <br />

Email: {{Email}}<br />

Nội dung: {{noidung}}<br />

</div>

</html>

Bước 4: Tạo GopYController.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using System.Configuration;

using Common;

using BanHangOnline.Models;

namespace BanHangOnline.Controllers

{

public class GopYController : Controller

{

// GET: YKien

public ActionResult Index()

{

return View();

}

protected void SetAlert(string message, string type)

{

TempData["AlertMessage"] = message;

if (type == "success")

{

TempData["AlertType"] = "alert-success";

}

else if (type == "warning")

{

TempData["AlertType"] = "alert-warning";

}

else if (type == "error")

{

TempData["AlertType"] = "alert-danger";

}

}

Bước 5: Trong thư mục Models tạo class EmailInfor.cs

Bước 6: Về Controller GopY Add View

Nội dung của View copy từ contact và sửa lại

@model BanHangOnline.Models.EmailInfor

@{

ViewBag.Title = "Index";

Layout = "~/Views/Shared/_Layout.cshtml";

}

<script src="~/Assets/Admin/js/Alert.js"></script>

@using (Html.BeginForm("Send", "GopY", FormMethod.Post))

{

@Html.AntiForgeryToken()

<div class="main">

<div class="content">

<div class="section group">

<div class="col span_2_of_3">

<div class="contact-form">

<div id="status_view">

@if (TempData["AlertMessage"] != null)

{

<div id="AlertBox" class="alert @TempData["AlertType"] hide">

@TempData["AlertMessage"]

</div>

}

</div>

<h2>Góp ý</h2>

<form role="form">

<div>

<span><label>Tên của bạn:</label></span>

@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })

</div>

<div>

<span><label>E-mail</label></span>

@Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })

</div>

<div>

<span><label>Phone</label></span>

@Html.EditorFor(model => model.Mobile, new { htmlAttributes = new { @class = "form-control" } })

</div>

<div>

<span><label>Nội dung góp ý</label></span>

@Html.TextBoxFor(model => model.Noidung, new { htmlAttributes = new { @class = "form-control" } })

</div>

<div>

<span><input type="submit" value="Gửi" class="myButton"></span>

</div>

</form>

</div>

</div>

<div class="col span_1_of_3">

<div class="contact_info">

<h3>Tìm địa chỉ Công ty</h3>

<div class="map">

<iframe width="100%" height="175" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="https://maps.google.co.in/maps?f=q&amp;source=s_q&amp;hl=en&amp;geocode=&amp;q=Lighthouse+Point,+FL,+United+States&amp;aq=4&amp;oq=light&amp;sll=26.275636,-80.087265&amp;sspn=0.04941,0.104628&amp;ie=UTF8&amp;hq=&amp;hnear=Lighthouse+Point,+Broward,+Florida,+United+States&amp;t=m&amp;z=14&amp;ll=26.275636,-80.087265&amp;output=embed"></iframe><br><small><a href="https://maps.google.co.in/maps?f=q&amp;source=embed&amp;hl=en&amp;geocode=&amp;q=Lighthouse+Point,+FL,+United+States&amp;aq=4&amp;oq=light&amp;sll=26.275636,-80.087265&amp;sspn=0.04941,0.104628&amp;ie=UTF8&amp;hq=&amp;hnear=Lighthouse+Point,+Broward,+Florida,+United+States&amp;t=m&amp;z=14&amp;ll=26.275636,-80.087265" style="color:#666;text-align:left;font-size:12px">View Larger Map</a></small>

</div>

</div>

<div class="company_address">

<h3>Company Information :</h3>

<p>500 Lorem Ipsum Dolor Sit,</p>

<p>22-56-2-9 Sit Amet, Lorem,</p>

<p>USA</p>

<p>Phone:(00) 222 666 444</p>

<p>Fax: (000) 000 00 00 0</p>

<p>Email: <span>[email protected]</span></p>

<p>Follow on: <span>Facebook</span>, <span>Twitter</span></p>

</div>

</div>

</div>

</div>

</div>

}

- Về Controller GopY viết tiếp

[HttpPost]

public ActionResult Send(EmailInfor EM)

{

try

{

string cus = EM.Name.ToString();

string phone = EM.Mobile.ToString();

string email = EM.Email.ToString();

string nd = EM.Noidung.ToString();

string content = System.IO.File.ReadAllText(Server.MapPath("~/Assets/Client/temp/GopY.html"));

content = content.Replace("{{CustomerName}}", cus);

content = content.Replace("{{Phone}}", phone);

content = content.Replace("{{Email}}", email);

content = content.Replace("{{noidung}}", nd);

var toEmail = ConfigurationManager.AppSettings["ToEmailAddress"].ToString();

new MailHelper().SendMail(email, "Cảm ơn bạn đã đóng góp ý kiến", content);

new MailHelper().SendMail(toEmail, "Đóng góp ý kiến từ bán hàng Online", content);

SetAlert("Gửi đi thành công", "success");

}

catch

{

SetAlert("Chưa được gửi", "error");

}

return View("Index");

}

}

}

Bước 7: Chạy chương trình và kiểm tra kết quả.

Mở hộp thư: [email protected] kiểm tra kết quả:

BÀI 22: TÍCH HỢP GOOGLE MAP API.

Yêu cầu của bài: Mở View GopY.cshtml thiết kế và viết code. Sau khi chạy:

Nhập dữ liệu cho bảng Company như sau:

Bước 1: Tạo CompanyDao.cs:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using KetNoiCSDL.EF;

namespace KetNoiCSDL.DAO

{

public class CompanyDao

{

BanhangOnlineDbContext db = null;

public CompanyDao()

{

db = new BanhangOnlineDbContext();

}

public Company Laycty()

{

return db.Company.Where(x => x.CompanyName != null).Single();

}

}

}

Bước 2: Mở GopYController.cs

Viết thêm ViewBag:

ViewBag.cty = new CompanyDao().Laycty();

Bước 3: Về View sửa lại

@model BanHangOnline.Models.EmailInfor

@{

ViewBag.Title = "Index";

Layout = "~/Views/Shared/_Layout.cshtml";

var Cty = (KetNoiCSDL.EF.Company)ViewBag.cty;

}

<style>

#mapCanvas {

height: 300px;

}

</style>

@section jsFooter{

<script src=""></script>

<script src="/assets/client/js/controller/contactController.js"></script>

<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB4snF4PWG0iYRFRr7O_BdTCefSW3kSiV4&callback=initMap"

type="text/javascript"></script>

<script>

//AIzaSyB4snF4PWG0iYRFRr7O_BdTCefSW3kSiV4

//21.043976, 105.866707

function initMap() {

var uluru = { lat: 21.043976, lng: 105.866707 };

var map = new google.maps.Map(document.getElementById('mapCanvas'), {

zoom: 16,

center: uluru

});

var contentString = '@Cty.CompanyName @Cty.Address';

var infowindow = new google.maps.InfoWindow({

content: contentString

});

var marker = new google.maps.Marker({

position: uluru,

map: map,

pre: 'Địa chỉ'

});

marker.addListener('click', function () {

infowindow.open(map, marker);

});

}

google.maps.event.addDomListener(window, 'load', initMap);

</script>

}

@using (Html.BeginForm("Send", "GopY", FormMethod.Post))

{

@Html.AntiForgeryToken()

<div class="main">

<div class="content">

<div class="section group">

<div class="col span_2_of_3">

<div class="contact-form">

<div id="status_view">

@if (TempData["AlertMessage"] != null)

{

<div id="AlertBox" class="alert @TempData["AlertType"] hide">

@TempData["AlertMessage"]

</div>

}

</div>

<h2>Góp ý</h2>

<form role="form">

<div>

<span><label>Tên của bạn:</label></span>

@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })

</div>

<div>

<span><label>E-mail</label></span>

@Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })

</div>

<div>

<span><label>Phone</label></span>

@Html.EditorFor(model => model.Mobile, new { htmlAttributes = new { @class = "form-control" } })

</div>

<div>

<span><label>Nội dung góp ý</label></span>

@Html.TextAreaFor(model => model.Noidung, new { htmlAttributes = new { @class = "form-control" } })

</div>

<div>

<span><input type="submit" value="Gửi" class="myButton"></span>

</div>

</form>

</div>

</div>

<div class="col span_1_of_3">

<div class="contact_info">

<h3>Địa chỉ Công ty</h3>

<div class="col-md-6">

<h3>Bản đồ</h3>

<div class="map" id="mapCanvas"></div>

</div>

</div>

<div class="company_address">

<h3>Thông tin về Công ty :</h3>

<p>Tên công ty: @Cty.CompanyName</p>

<p>Địa chỉ: @Cty.Address</p>

<p>Email: <span>@Cty.Email</span></p>

<p>Phone: @Cty.Phone</p>

<p>Follow on: <span>Facebook</span>, <span>Twitter</span></p>

</div>

</div>

</div>

</div>

</div>

}

Chú ý: Để lấy được đoạn code chèn bản đồ ở trên bạn làm như sau:

Tìm đến trang Google map API

Chọn WEB

Chọn SAMPLES\Infor windows

Copy đoạn code trên, rồi sửa lại.

Bước 4: vào trang _Layout.html

Viết thêm: @RenderSection("jsFooter", required: false)

Bước 5: Chạy chương trình.

BÀI 23: TẠO FORM ĐĂNG KÝ THÀNH VIÊN CÓ TÍCH HỢP CAPTCHA

1. Tạo form đăng ký thành viên.

Bước 1: Tạo Models\RegisterModel.cs

using System;

using System.Collections.Generic;

using System.ComponentModel.DataAnnotations;

using System.Linq;

using System.Web;

namespace BanHangOnline.Models

{

public class RegisterModel

{

[Key]

public long ID { set; get; }

[Display(Name = "Tên đăng nhập")]

[Required(ErrorMessage = "Yêu cầu nhập tên đăng nhập")]

public string UserName { set; get; }

[Display(Name = "Mật khẩu")]

[StringLength(20, MinimumLength = 6, ErrorMessage = "Độ dài mật khẩu ít nhất 6 ký tự.")]

[Required(ErrorMessage = "Yêu cầu nhập mật khẩu")]

public string Password { set; get; }

[Display(Name = "Xác nhận mật khẩu")]

[Compare("Password", ErrorMessage = "Xác nhận mật khẩu không đúng.")]

public string ConfirmPassword { set; get; }

[Display(Name = "Họ tên")]

[Required(ErrorMessage = "Yêu cầu nhập họ tên")]

public string Name { set; get; }

[Display(Name = "Địa chỉ")]

public string Address { set; get; }

[Required(ErrorMessage = "Yêu cầu nhập email")]

[Display(Name = "Email")]

public string Email { set; get; }

[Display(Name = "Điện thoại")]

public string Phone { set; get; }

[Display(Name="Tỉnh/thành")]

public string ProvinceID { set; get; }

[Display(Name = "Quận/Quyện")]

public string DistrictID { set; get; }

}

}

Bước 2: Vào UserDao tạo thêm 2 phương thức sau:

public bool CheckUserName(string userName)

{

return db.User.Count(x => x.UserName == userName) > 0;

}

public bool CheckEmail(string email)

{

return db.User.Count(x => x.Email == email) > 0;

}

Bước 3: Tạo UserController.cs

[HttpGet]

public ActionResult Register()

{

return View();

}

Bước 4: Add View Register.schtml

@model BanHangOnline.Models.RegisterModel

@{

ViewBag.Title = "Register";

Layout = "~/Views/Shared/_Layout.cshtml";

}

@using (Html.BeginForm("Register", "User", FormMethod.Post))

{

@Html.AntiForgeryToken()

<div class="main">

<div class="content">

<div class="section group">

<div class="col span_2_of_3">

<div class="contact-form">

<div id="status_view">

@if (TempData["AlertMessage"] != null)

{

<div id="AlertBox" class="alert @TempData["AlertType"] hide">

@TempData["AlertMessage"]

</div>

}

</div>

<h2>Đăng ký thành viên</h2>

<div class="form-group">

<div>

@if (ViewBag.Success != null)

{<div class="alert alert-success">@ViewBag.Success</div> }

</div>

<div class="form-group">

@Html.LabelFor(model => model.UserName, new { @class = "control-label col-md-2" })

<div class="col-md-10">

@Html.TextBoxFor(model => model.UserName, new { @class = "form-control" })

@Html.ValidationMessageFor(model => model.UserName, "", new { @class = "text-danger" })

</div>

</div>

<div class="form-group">

@Html.LabelFor(model => model.Password, new { @class = "control-label col-md-2" })

<div class="col-md-10">

@Html.PasswordFor(model => model.Password, new { @class = "form-control" })

@Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })

</div>

</div>

<div class="form-group">

@Html.LabelFor(model => model.ConfirmPassword, new { @class = "control-label col-md-2" })

<div class="col-md-10">

@Html.PasswordFor(model => model.ConfirmPassword, new { @class = "form-control" })

@Html.ValidationMessageFor(model => model.ConfirmPassword, "", new { @class = "text-danger" })

</div>

</div>

<div class="form-group">

@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })

<div class="col-md-10">

@Html.TextBoxFor(model => model.Name, new { @class = "form-control" })

@Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })

</div>

</div>

<div class="form-group">

@Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })

<div class="col-md-10">

@Html.TextAreaFor(model => model.Address, new { @class = "form-control" })

@Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })

</div>

</div>

<div class="form-group">

@Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })

<div class="col-md-10">

@Html.TextBoxFor(model => model.Email, new { @class = "form-control" })

@Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })

</div>

</div>

<div class="form-group">

@Html.LabelFor(model => model.Phone, htmlAttributes: new { @class = "control-label col-md-2" })

<div class="col-md-10">

@Html.TextBoxFor(model => model.Phone, new { @class = "form-control" })

@Html.ValidationMessageFor(model => model.Phone, "", new { @class = "text-danger" })

</div>

</div>

@* Captcha lát nữa sẽ thêm chỗ này *@

<div class="form-group">

<div class="col-md-offset-2 col-md-10">

<input type="submit" value="Đăng ký" class="btn btn-primary" />

</div>

</div>

</div>

</div>

</div>

</div>

</div>

</div>

}

Bước 5: Vào UserController Viết phương thức [Httpost]

[HttpPost]

public ActionResult Register(RegisterModel model)

{

if (ModelState.IsValid)

{

var dao = new UserDao();

if (dao.CheckUserName(model.UserName))

{

ModelState.AddModelError("", "Tên đăng nhập đã tồn tại");

}

else if (dao.CheckEmail(model.Email))

{

ModelState.AddModelError("", "Email đã tồn tại");

}

else

{

var user = new User();

user.UserName = model.UserName;

user.Name = model.Name;

user.Password = MaHoaMd5.MD5Hash(model.Password);

user.Phone = model.Phone;

user.Email = model.Email;

user.Address = model.Address;

user.CreatedDate = DateTime.Now;

user.Status = true;

var result = dao.Insert(user);

if (result > 0)

{

ViewBag.Success = "Đăng ký thành công";

model = new RegisterModel();

}

else

{

ModelState.AddModelError("", "Đăng ký không thành công.");

}

}

}

return View("Register");

}

Bước 6: Khai báo trong RouterConfig.

routes.MapRoute(

name: "Dang ky thanh vien",

url: "dang-ky",

defaults: new { controller = "User", action = "Register", id = UrlParameter.Optional },

namespaces: new[] { "BanHangOnline.Controllers" }

);

Bước 7: Chạy chương trình. Sau khi chương trình chạy đúng rồi thì ta tiến hành chèn Captcha.

2. Chèn CaptCha

Bước 1: Install BotDetect

Sau khi cài đặt mở Web.config kiểm tra xem:

<system.web>

<httpHandlers>

<!-- Register the HttpHandler used for BotDetect Captcha

requests -->

<add verb="GET" path="BotDetectCaptcha.ashx" type="BotDetect.Web.CaptchaHandler, BotDetect" />

</httpHandlers>

<system.webServer>

<validation validateIntegratedModeConfiguration="false" />

<handlers>

<!-- Register the HttpHandler used for BotDetect Captcha

requests (IIS 7.0+) -->

<remove name="BotDetectCaptchaHandler" />

<add name="BotDetectCaptchaHandler" preCondition="integratedMode" verb="GET" path="BotDetectCaptcha.ashx" type="BotDetect.Web.CaptchaHandler, BotDetect" />

</handlers>

Bước 2: Vào Register.cshtml khai báo thư viện captcha.

@model BanHangOnline.Models.RegisterModel

@using BotDetect.Web.Mvc;

<link href="@BotDetect.Web.CaptchaUrls.Absolute.LayoutStyleSheetUrl"

rel="stylesheet" type="none" />

@{ MvcCaptcha registerCapcha = new MvcCaptcha("registerCapcha"); }

@{

ViewBag.Title = "Register";

Layout = "~/Views/Shared/_Layout.cshtml";

}

Hiển thị captcha

<div class="form-group">

<div class="col-md-offset-2 col-md-10">

@Html.Captcha(registerCapcha)

@Html.TextBox("CaptchaCode")

</div>

</div>

Bước 3: Vào UserController.cs Viết thêm

[CaptchaValidation("CaptchaCode", "registerCapcha", "Mã xác nhận không đúng!")]

Bước 4: Thêm dòng lệnh sau vào file RouteConfig.cs

routes.IgnoreRoute("{*botdetect}",

new { botdetect = @"(.*)BotDetectCaptcha\.ashx" });

Bước 5: Chạy chương trình

Bài tập làm thêm.

Vào trang https://w3layouts.com/ tìm kiếm mẫu form register

Download mẫu trên rồi đưa vào chương trình. Sản phẩm sau khi hoàn thành:

BÀI 24: TẠO TRANG ĐĂNG NHẬP VÀ ĐĂNG XUẤT CHO KHÁCH.

Bước 1: Tạo Models/LoginModel.cs

using System;

using System.Collections.Generic;

using System.ComponentModel.DataAnnotations;

using System.Linq;

using System.Web;

namespace BanHangOnline.Models

{

public class LoginModel

{

[Key]

[Display(Name = "Tên đăng nhập")]

[Required(ErrorMessage = "Bạn phải nhập tài khoản")]

public string UserName { set; get; }

[Required(ErrorMessage = "Bạn phải nhập mật khẩu")]

[Display(Name = "Mật khẩu")]

public string Password { set; get; }

}

}

Sau khi tạo xong nhớ Build lại chương trình.

Bước 2: Vào UserController.cs tạo phương thức:

public ActionResult Login()

{

return View();

}

Bước 3: Add mới 1 View Login

Sửa lại code cho View:

@model BanHangOnline.Models.LoginModel

@{

ViewBag.Title = "Login";

Layout = "~/Views/Shared/_Layout.cshtml";

}

<div class="content">

@using (Html.BeginForm("Login", "User", FormMethod.Post))

{

@Html.AntiForgeryToken()

<div class="form-horizontal">

<h4>Đăng nhập</h4>

<hr />

<div class="form-group">

<label class="control-label col-md-2"></label>

<div class="col-md-10">

@Html.ValidationSummary(true, "", new { @class = "text-danger" })

</div>

</div>

<div class="form-group">

@Html.LabelFor(model => model.UserName, htmlAttributes: new { @class = "control-label col-md-2" })

<div class="col-md-10">

@Html.TextBoxFor(model => model.UserName, new { @class = "form-control" })

@Html.ValidationMessageFor(model => model.UserName, "", new { @class = "text-danger" })

</div>

</div>

<div class="form-group">

@Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })

<div class="col-md-10">

@Html.PasswordFor(model => model.Password, new { @class = "form-control" })

@Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })

</div>

</div>

<div class="form-group">

<div class="col-md-offset-2 col-md-10">

<input type="submit" value="Đăng nhập" class="btn btn-primary" />

</div>

</div>

</div>

}

</div>

Bước 4: Mở UserController. Viết phương thức HttpPost cho Login

[HttpPost]

public ActionResult Login(LoginModel model)

{

if (ModelState.IsValid)

{

var dao = new UserDao();

var result = dao.Login(model.UserName, MaHoaMd5.MD5Hash(model.Password));

if (result == 1)

{

var user = dao.GetByID(model.UserName);

var userSession = new UserLogin();

userSession.UserName = user.UserName;

userSession.UserID = user.ID;

Session.Add(CommonConstants.USER_SESSION, userSession);

return Redirect("/");

}

else if (result == 0)

{

ModelState.AddModelError("", "Tài khoản không tồn tại.");

}

else if (result == -1)

{

ModelState.AddModelError("", "Tài khoản đang bị khoá.");

}

else if (result == -2)

{

ModelState.AddModelError("", "Mật khẩu không đúng.");

}

else

{

ModelState.AddModelError("", "đăng nhập không đúng.");

}

}

return View();

}

Bước 5: Mở RouterConfig viết thêm

routes.MapRoute(

name: "Dang nhap",

url: "Dang-nhap",

defaults: new { controller = "User", action = "Login", id = UrlParameter.Optional },

namespaces: new[] { "BanHangOnline.Controllers" }

);

Bước 6: Mở TopMenu.cshtml viết thêm:

@model List<KetNoiCSDL.EF.Menu>

<div class="call">

<p><span>Nếu bạn cần?</span> Xin hãy gọi <span class="number">0978-187-154</span></span></p>

</div>

<div class="account_desc">

@{

var session = (BanHangOnline.Common.UserLogin)Session[BanHangOnline.Common.CommonConstants.USER_SESSION];

}

@if (session == null)

{

<ul>

@foreach (var item in Model)

{

<li><a href="@item.Link" target="@item.Target">@item.Text</a></li>

}

</ul>

}

else

{

<ul>

<li>Xin chào:@session.UserName</li>

<li>@Html.ActionLink("Thoát", "Logout", "User")</li>

</ul>

}

</div>

<div class="clear"></div>

Bước 7: Mở UserController. Viết phương thức Logout

public ActionResult Logout()

{

Session[CommonConstants.USER_SESSION] = null;

return Redirect("/");

}

Bước 8: Chạy chương trình.

Chọn Đăng nhập.

Đăng nhập thành công, Kích Thoát

BÀI 25 ĐĂNG NHẬP BẰNG TÀI KHOẢN FACEBOOK

Bước 1: Truy cập vào trang https://developers.facebook.com

Kích vào Cài đặt

Nhập đầy đủ thông tin: Miền ứng dụng, ta copy Local host.

Kích vào Hiển thị

Bước 2: Vào Web.Config thiết lập

<add key="FbAppId" value="251739685346369"/>

<add key ="FbAppSecret" value="121915bbbbcaa3ec694a3628804147c4"/>

Bước 3: Vào cài đặt Facebook

Bước 4: Vào trang Login thiết kế nút đăng nhập:

<a class="btn btn-facebook" href="/User/LoginFacebook"> Đăng nhập bằng Facebook </a>

Bước 5: Vào UserDao.cs viết phương thức:

public long InsertForFacebook(User entity)

{

var user = db.User.SingleOrDefault(x => x.UserName == entity.UserName);

if (user == null)

{

db.User.Add(entity);

db.SaveChanges();

return entity.ID;

}

else

{

return user.ID;

}

}

Bước 6: Vào UserController.cs Viết 2 phương thức:

public ActionResult LoginFacebook()

{

var fb = new FacebookClient();

var loginUrl = fb.GetLoginUrl(new

{

client_id = ConfigurationManager.AppSettings["FbAppId"],

client_secret = ConfigurationManager.AppSettings["FbAppSecret"],

redirect_uri = RedirectUri.AbsoluteUri,

response_type = "code",

scope = "email",

});

return Redirect(loginUrl.AbsoluteUri);

}

public ActionResult FacebookCallback(string code)

{

var fb = new FacebookClient();

dynamic result = fb.Post("oauth/access_token", new

{

client_id = ConfigurationManager.AppSettings["FbAppId"],

client_secret = ConfigurationManager.AppSettings["FbAppSecret"],

redirect_uri = RedirectUri.AbsoluteUri,

code = code

});

var accessToken = result.access_token;

if (!string.IsNullOrEmpty(accessToken))

{

fb.AccessToken = accessToken;

// Get the user's information, like email, first name, middle name etc

dynamic me = fb.Get("me?fields=first_name,middle_name,last_name,id,email");

string email = me.email;

string userName = me.email;

string firstname = me.first_name;

string middlename = me.middle_name;

string lastname = me.last_name;

var user = new User();

user.Email = email;

user.UserName = email;

user.Status = true;

user.Name = firstname + " " + middlename + " " + lastname;

user.CreatedDate = DateTime.Now;

var resultInsert = new UserDao().InsertForFacebook(user);

if (resultInsert > 0)

{

var userSession = new UserLogin();

userSession.UserName = user.UserName;

userSession.UserID = user.ID;

Session.Add(CommonConstants.USER_SESSION, userSession);

}

}

return Redirect("/");

}

Viết RedirectUri

private Uri RedirectUri

{

get

{

var uriBuilder = new UriBuilder(Request.Url);

uriBuilder.Query = null;

uriBuilder.Fragment = null;

uriBuilder.Path = Url.Action("FacebookCallback");

return uriBuilder.Uri;

}

}

Bước 7: Chạy chương trình

Bài tập làm thêm:

Vào trang https://w3layouts.com tìm kiếm login, download mẫu form sau:

Sử dụng mẫu form này, cho Form đăng nhập.

Sau khi chỉnh sửa:

BÀI 26: CÁCH ĐỌC FILE XML RA DROP DOWN LIST BẰNG AJAX

Sử dụng 1 file XML lấy dữ liệu ra cho Tỉnh và huyện như sau:

Cho 1 file dữ liệu tỉnh và quận huyện : Provinces_Data.xml.

Copy file này vào \Assets\Client\data\Provinces_Data.xml

Bước 1: Vào View Register.cshtml viết thêm 2 trường sau:

<div class="icon1">

<i class="fa fa-user" aria-hidden="true"></i>

@Html.LabelFor(model => model.ProvinceID)

@Html.DropDownList("ProvinceID", new SelectList(new string[] { }), new { @class = "form-control", @id = "ddlProvince" })

</div>

<div class="icon1">

<i class="fa fa-user" aria-hidden="true"></i>

@Html.LabelFor(model => model.DistrictID)

@Html.DropDownList("DistrictID", new SelectList(new string[] { }), new { @class = "form-control", @id = "ddlDistrict" })

</div>

Bước 2: Tạo 2 Models:

+ ProvinceModel.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

namespace BanHangOnline.Models

{

public class ProvinceModel

{

public int ID { set; get; }

public string ProvinceName { set; get; }

}

}

+ DistrictModel.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

namespace BanHangOnline.Models

{

public class DistrictModel

{

public int ID { set; get; }

public string DistrictName { set; get; }

public int ProvinceID { set; get; }

}

}

Bước 3: Tạo file \Assets\Client\js\controller\ userController.js

var user = {

init: function () {

user.loadProvince();

user.registerEvent();

},

registerEvent: function () {

$('#ddlProvince').off('change').on('change', function () {

var id = $(this).val();

if (id != '') {

user.loadDistrict(parseInt(id));

}

else {

$('#ddlDistrict').html('');

}

});

},

loadProvince: function () {

$.ajax({

url: '/User/LoadProvince',

type: "POST",

dataType: "json",

success: function (response) {

if (response.status == true) {

var html = '<option value="">--Chọn tỉnh thành--</option>';

var data = response.data;

$.each(data, function (i, item) {

html += '<option value="' + item.ID + '">' + item.ProvinceName + '</option>'

});

$('#ddlProvince').html(html);

}

}

})

},

loadDistrict: function (id) {

$.ajax({

url: 'User/LoadDistrict',

type: "POST",

data: { ProvinceID: id },

dataType: "json",

success: function (response) {

if (response.status == true) {

var html = '<option value="">--Chọn quận huyện--</option>';

var data = response.data;

$.each(data, function (i, item) {

html += '<option value="' + item.ID + '">' + item.DistrictName + '</option>'

});

$('#ddlDistrict').html(html);

}

}

})

}

}

user.init();

Bước 4: Vào UserController viết 2 phương thức LoadProvince và LoadDistrict

//Lấy tỉnh

public JsonResult LoadProvince()

{

var xmlDoc = XDocument.Load(Server.MapPath(@"/Assets/client/data/Provinces_Data.xml"));

var xElements = xmlDoc.Element("Root").Elements("Item").Where(x => x.Attribute("type").Value == "province");

var list = new List<ProvinceModel>();

ProvinceModel province = null;

foreach (var item in xElements)

{

province = new ProvinceModel();

province.ID = int.Parse(item.Attribute("id").Value);

province.ProvinceName = item.Attribute("value").Value;

list.Add(province);

}

return Json(new

{

data = list,

status = true

});

}

//Lấy Quận/huyện

public JsonResult LoadDistrict(int provinceID)

{

var xmlDoc = XDocument.Load(Server.MapPath(@"/Assets/Client/data/Provinces_Data.xml"));

var xElement = xmlDoc.Element("Root").Elements("Item")

.Single(x => x.Attribute("type").Value == "province" && int.Parse(x.Attribute("id").Value) == provinceID);

var list = new List<DistrictModel>();

DistrictModel district = null;

foreach (var item in xElement.Elements("Item").Where(x => x.Attribute("type").Value == "district"))

{

district = new DistrictModel();

district.ID = int.Parse(item.Attribute("id").Value);

district.DistrictName = item.Attribute("value").Value;

district.ProvinceID = int.Parse(xElement.Attribute("id").Value);

list.Add(district);

}

return Json(new

{

data = list,

status = true

});

}

Bước 5: Trong UserController Viết thêm để insert mã tỉnh và mã huyện vào bảng User

if (!string.IsNullOrEmpty(model.ProvinceID))

{

user.ProvinceID = int.Parse(model.ProvinceID);

}

if (!string.IsNullOrEmpty(model.DistrictID))

{

user.DistrictID = int.Parse(model.DistrictID);

}

Bước 6: Vào View Register.cshtml thêm thư viện:

<script src="/Assets/Client/js/jquery-3.2.1.min.js"></script>

<script src="/Assets/Client/js/controller/userController.js"></script>

Bước 7: Chạy chương trình.

BÀI 27: CÁCH SỬ DỤNG OUTPUTCACHE ĐỂ TĂNG TỐC ĐỘ

Cú pháp:

Trong đó :

+ Duration : là thời gian cache được tính bằng giây.

+ Location : Vị trí cache gồm :

Any: Bất kỳ vị trí nào (Mặc định)

Client: Cache ở máy trạm

Downstream:

None:

Server:

ServerAndClient:

+ Nostore:

+ Order:

+ SqlDependency:

+ VaryByContenEncoding:

+ VaryByCustom:

+ VaryByHeader:

+ VaryByParam:

Thực hiện như sau :

Cách 1: Đưa trực tiếp vào Controller.

Bước 1: Vào HomeController.cs khai báo

[OutputCache (Duration=3600, Location =System.Web.UI.OutputCacheLocation.Client) ]

Cách 2: Đưa vào Webconfig.

Bước 1: Mở Web.config tìm đến thẻ <system.web> khai báo thêm thẻ <caching>

<caching>

<outputCacheSettings>

<outputCachePro/files>

<add name ="1hour" duration="3600" location="Client" varyByParam="none"/>

<add name ="1day" duration="86400" location="Server"/>

</outputCachePro/files>

</outputCacheSettings>

</caching>

Bước 2: Về HomeController:

[OutputCache(CacheProfile ="1hour")]

Tương tự các bạn có thể caching tại những vị trí khác.

BÀI 28: PHÂN QUYỀN CHO NGƯỜI DÙNG.

1. Phân quyền truy cập vào trang Admin

Tạo thêm 3 bảng sau:

-Role

-UserGroup

-Credential

Nhập dữ liệu:

Vào bảng User trường GroupID gõ MEMBER như hình dưới

Bước 1: Tạo mới một class Constans.cs trong Common

Bước 2: Vào UserDao.cs Viết lại phương thức Login

public int Login(string userName, string passWord, bool isLoginAdmin = false)

{

var result = db.Users.SingleOrDefault(x => x.UserName == userName);

if (result == null)

{

return 0;

}

else

{

if (isLoginAdmin == true)

{

if (result.GroupID == CommonConstants.ADMIN_GROUP || result.GroupID == CommonConstants.MOD_GROUP)

{

if (result.Status == false)

{

return -1;

}

else

{

if (result.Password == passWord)

return 1;

else

return -2;

}

}

else

{

return -3;

}

}

else

{

if (result.Status == false)

{

return -1;

}

else

{

if (result.Password == passWord)

return 1;

else

return -2;

}

}

}

}

Bước 3: Vào LoginController.cs Viết thêm vào phương thức Login như sau:

var res = dao.Login(model.UserName, MaHoaMd5.MD5Hash(model.PassWord),true);

else if (res == -3)

{

ModelState.AddModelError("", "Bạn không có quyền đăng nhập.");

}

else

Kết quả như sau:

public ActionResult Login(LoginModel model)

{

if (ModelState.IsValid)

{

var dao = new UserDao();

var res = dao.Login(model.UserName, MaHoaMd5.MD5Hash(model.PassWord),true);

if (res == 1)

{

var user = dao.GetByID(model.UserName);

var userSession = new UserLogin();

userSession.UserName = user.UserName;

userSession.UserID = user.ID;

Session.Add(CommonConstants.USER_SESSION, userSession);

return RedirectToAction("Index", "Home");

}

else if (res == 0)

{

ModelState.AddModelError("", "Tài khoản không tồn tại.");

}

else if (res == -1)

{

ModelState.AddModelError("", "Tài khoản đang bị khóa.");

}

else if (res == -2)

{

ModelState.AddModelError("", "Mật khẩu không đúng.");

}

else if (res == -3)

{

ModelState.AddModelError("", "Bạn không có quyền đăng nhập.");

}

else

{

ModelState.AddModelError("", "Đăng nhập không đúng.");

}

}

return View("Login");

}

Bước 4: Chạy chương trình

Vào CSDL sửa lại 1 quyền bất kỳ là ADMIN

Đăng nhập lại sẽ thành công!

2. Phân quyền chi tiết cho quản trị

Bước 1: Mở UserDao.cs. Viết thêm phương thức

//Phân quyền người dùng

public List<string> GetListCredential(string userName)

{

var user = db.User.Single(x => x.UserName == userName);

var data = (from a in db.Credential

join b in db.UserGroup on a.UserGroupID equals b.ID

join c in db.Role on a.RoleID equals c.ID

where b.ID == user.GroupID

select new

{

RoleID = a.RoleID,

UserGroupID = a.UserGroupID

}).AsEnumerable().Select(x => new Credential()

{

RoleID = x.RoleID,

UserGroupID = x.UserGroupID

});

return data.Select(x => x.RoleID).ToList();

}

Bước 2: Vào EF\Credential.cs. Khai báo thêm [Serializable]

Bước 3: Vào Common\ CommonConstants.cs Khai báo thêm:

public static string SESSION_CREDENTIALS = "SESSION_CREDENTIALS";

Bước 4: Tạo mới Class HasCredentialAttribute.cs trong Common

Viết code cho class HasCredentialAttribute.cs như sau:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using Common;

using System.Web.Routing;

using BanHangOnline.Common;

namespace BanhangOnline

{

public class HasCredentialAttribute : AuthorizeAttribute

{

public string RoleID { set; get; }

protected override bool AuthorizeCore(HttpContextBase httpContext)

{

var session = (UserLogin)HttpContext.Current.Session[CommonConstants.USER_SESSION];

if (session == null)

{

return false;

}

List<string> privilegeLevels = this.GetCredentialByLoggedInUser(session.UserName);

// Call another method to get rights of the user from DB

if (privilegeLevels.Contains(this.RoleID) || session.GroupID == Common.Constants.ADMIN_GROUP)

{

return true;

}

else

{

return false;

}

}

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)

{

filterContext.Result = new ViewResult

{

ViewName = "/Areas/Admin/Views/Shared/401.cshtml"

};

}

private List<string> GetCredentialByLoggedInUser(string userName)

{

var credentials = (List<string>)HttpContext.Current.Session[CommonConstants.SESSION_CREDENTIALS];

return credentials;

}

}

}

Bước 5: Tạo mới View 401.cshtml

@{

ViewBag.Title = "View";

Layout = "/Areas/Admin/Views/Shared/_Layout.cshtml";

}

<div class="alert alert-danger">

Bạn không có quyền truy cập.

</div>

Bước 6: Chạy chương trình:

- Đăng nhập User TruongPhi được phân quyền là MOD sẽ không vào xem được danh sách user.

- Đăng nhập User quyền ADMIN sẽ xem được:

Phần Quyền lại cho MOD ở bảng Credential. Chạy lại để xem kết quả.

BÀI 29: TỐI ƯU HÓA ĐƯỜNG TRUYỀN BẰNG CÁCH NÉN CSS VÀ JAVASCRIPT

Bước 1: Install Nuget Asp.net.Web.Optimization như hình dưới.

Bước 2: Trong thư mục App_Start tạo mới 1 class BundleConfig.cs

Trong Class BundleConfig.cs viết các phương thức thay thế cho css hay JavaScript như sau:

using System.Web.Optimization;

namespace BanHangOnline.App_Start

{

public class BundleConfig

{

public static void RegisterBundles(BundleCollection bundles)

{

bundles.Add(new ScriptBundle("~/bundles/jquery").Include(

"~/assets/Client/js/jquery-1.7.2.min.js",

"~/assets/Client/js/move-top.js",

"~/assets/Client/js/easing.js",

"~/assets/Client/js/startstop-slider.js",

"~/assets/Client/js/slides.min.jquery.js"

));

bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(

"~/Assets/Client/css/boostrap-social.css"

));

bundles.Add(new StyleBundle("~/bundles/css").Include(

"~/assets/Client/css/style.css",

"~/assets/Client/css/slider.css",

"~/Assets/Client/css/global.css"));

}

}

}

Bước 3: Qua trang _Layout.cshtml thay thế:

@Styles.Render("~/bundles/css")

@Styles.Render("~/bundles/bootstrap") @Scripts.Render("~/bundles/jquery")

Chú ý:

- Vào ~\View\Web.config viết thêm lệnh

<add namespace="System.Web.Optimization"/>

- Vào Global.asax viết thêm lệnh

BundleConfig.RegisterBundles(BundleTable.Bundles);

Bước 4: Chạy chương trình. Nhấn phím F12

BÀI 30: CÁC QUY TẮC TỐI TƯU CHO SEO (Search Engine Optimization)

160

Lập trình Web2 – ASP.NET MVC

Giáo viên: Thái Ngô Hùng – Biên soạn.