新建BaseController 控制器
using Login.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;namespace Login.Controllers
{
public class BaseController : Controller
{
public bool IsCheckLogin = true;public static UserInfo BaseUserInfo { get; set; }
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);if (IsCheckLogin)
{
if (BaseUserInfo == null)
{
filterContext.HttpContext.Response.Redirect("/User/Login");
}
}
}
}
}
UserController登录控制器
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Login.Models;
using Login.ViewModel;namespace Login.Controllers
{
public class UserController : BaseController
{
public UserController()
{
IsCheckLogin = false;
}
public ActionResult Login()
{
return View();
}[HttpPost]
public ActionResult Login(LoginViewModel Login)
{
if (ModelState.IsValid)
{
UserEntity db = new UserEntity();
var user = db.UserInfo.FirstOrDefault(u => u.UserName == Login.UserName && u.Password == Login.Password);
if (user != null)
{
BaseUserInfo = user;
return RedirectToAction("ProductAll", "Home");
}
else
{
ViewBag.LoginState = Login.UserName + "用户不存在...";
}
}
else
{
ModelState.AddModelError("", "登录失败");
}
return View();
}
}
}
HomeController控制器
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Login.Models;
using Login.ViewModel;namespace Login.Controllers
{
public class HomeController : BaseController
{public ActionResult ProductAll()
{
UserEntity db = new UserEntity();
ViewBag.CategoryList = db.Category.ToList();
return View();
}
public ActionResult GetProductAll()
{
UserEntity db = new UserEntity();
var list = db.Product.Select(b => new ProductListViewModel()
{ProductID = b.ProductID,
ProductName = b.ProductName,
IsUp = b.IsUp,
UnitPrice = b.UnitPrice,
Remark = b.Remark,
CategoryName = b.Category.CategoryName}).ToList();
ViewBag.CategoryList = db.Category.ToList();
return Json(list, JsonRequestBehavior.AllowGet);}
}}