Achieve Logon
This article simply implements the background login function, with no technical content
First, add a LogOnViewModel class to the Model folder in the LiveText. WebUI project. The Code is as follows:
Public class LogOnViewModel {[Required (ErrorMessage = "cannot be blank")] public string UserName {get; set;} [Required (ErrorMessage = "cannot be blank")] [DataType (DataType. password)] public string Password {get; set ;}}
Second, add an AccountController and select Empty controller in the Scaffolding option Template, as shown in:
The code in AccountController is also very simple. It is mainly a logon action and an exit action. The following code is specific:
Public class AccountController: Controller
{
Private LiveTextDbContext context = new LiveTextDbContext ();
//
// GET:/Account/LogOn
Public ActionResult LogOn ()
{
Return View ();
}
//
// POST:/Account/LogOn
[HttpPost]
Public ActionResult LogOn (LogOnViewModel model)
{
If (ModelState. IsValid)
{
If (context. Users. Any (u => u. UserName = model. UserName & u. Password = model. Password ))
{
FormsAuthentication. SetAuthCookie (model. UserName, false );
Return View ("~ /Views/Admin/Index. cshtml ");
}
Else
{
ModelState. AddModelError ("", "incorrect user name or password ");
}
}
Return View (model );
}
Public ActionResult LogOff ()
{
FormsAuthentication. SignOut ();
Return View ("LogOn ");
}
In LogOn action, if the user name and password provided by the user are correct, the page will jump to Index. cshtml. Index. cshtml in the Admin folder of the View folder, Admin is the folder I created.
Third, right-click LogOn and select AddView. the default option is used. After adding the option, the Account folder and LogOn. cshtml in the Account folder are automatically generated in the View folder.
Fourth, in LogOn. cshtml, I randomly found a template on the Internet and added it. You can download the source code to see the specific code. Below I will only post the key code:
@ Html. EditorFor (u => u. UserName)
@ Html. ValidationMessageFor (u => u. UserName)
@ Html. EditorFor (u => u. Password)
@ Html. ValidationMessageFor (u => u. Password) let's take a look at the running effect:
Logon page
Enter username: admin Password: admin Logon successful
Source code: http://files.cnblogs.com/nianming/LiveText20111020.rar
Author: Tian Nian-Ming