使用MVC模仿模板文件做了一个用户的登录,注册,修改密码的功能
Controller
using System;DbMVCEntities context = new DbMVCEntities();
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using MvcTest.Models;
namespace MvcTest.Controllers
{
public class DBAccountController : Controller
{
//
// GET: /DBAccount/
public ActionResult Login()
{
return View("Login");
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Login(string username,string password)
{
int count = (from e in context.Usr
where e.username == username
where e.password == password
select e).Count();
if (count.Equals(0))
{
ModelState.AddModelError("username", "用?户?名?或?密?码?错?误?");
return View("Login");
}
else
{
TempData["Message"] = string.Format("用?户?名?为?{0}的?用?户?登?陆?成?功?!", username);
return RedirectToAction("LogInSuccess", "DBAccount");
}
}
public ActionResult Register()
{
return View("Register");
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Register(string username, string password, string confirmPassword, string email)
{
DbMVCEntities context = new DbMVCEntities();
if (password.Equals(confirmPassword))
{
//Usr newUser = Usr.CreateUsr(username, password, email);
Usr newUser = new Usr();
newUser.username = username;
newUser.password = password;
newUser.Email = email;
context.AddToUsr(newUser);
context.SaveChanges();
TempData["Message"] =string.Format("用?户?名?为?{0}的?用?户?注?册?成?功?!",username);
return RedirectToAction("LogInSuccess", "DBAccount");
}
else
{
ViewData.ModelState.AddModelError("password", "请?两?次?输?入?的?密?码?相?同?!");
return View("Register");
}
}
public ActionResult LogInSuccess()
{
ViewData["Message"] = TempData["Message"];
return View("LogInSuccess");
}
public ActionResult ChangePassword()
{
return View("ChangePassword");
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ChangePassword(string currentPassword, string newPassword, string confirmPassword)
{
if (newPassword.Equals(confirmPassword))
{
}
return RedirectToAction("LogInSuccess", "DBAccount");
}
}
}
View界面就复制了原来模板中的View
添加了一个这个View
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
<title>LogInSuccess</title>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>LogInSuccess</h2>
<p><%=ViewData["Message"] %></p>
</asp:Content>
上面的代码,关注的重点其实有两个
- 函数前的[AcceptVerbs(HttpVerbs.Post)] 针对统一ActionName,通过不同的方法实现提交和展示
- HtmlHelper后面生成的空间名和函数中的参数是对应的,不需要再进行配置(约定优于配置)
- 推荐大家看老赵的webcast