MVC4 Making Web Tutorials Chapter II part of the user function to implement code _ practical skills

Source: Internet
Author: User

The features to be implemented by the user section are:
Order
First, users
1.1 User Registration
1.2 User Login
1.3 Password Change
1.4 Modification of information

To achieve these goals, first create the user (model) models

<summary>///User Model///</summary> public class User {[Key] public int UserId {get; set;} <summary>///user Group ID///</summary> [Display (name= user group ID)] [Required (errormessage = "x")] public int
 GroupId {get; set;} <summary>///username///</summary> [Display name= ' username ', description= ' 4-20 characters. ")] [Required (errormessage =" x ")] [Stringlength (minimumlength = 4, errormessage =" x ")] public string UserName {g Et Set ///<summary>///password///</summary> [Required] [Stringlength (256)] public string Password {get; set;
 ///<summary>///Sex "0-male; 1-female; 2-Confidential"///</summary> [Display (name= "Gender")] [Required (errormessage = "x")]]
 [Range (0,2,errormessage = "x")] public byte Gender {get; set;} <summary>///Email///</summary> [Display (name= "email", description= "Please enter your usual email.") ")] [Required (errormessage =" x ")] [EmailAddress (errormessage =" x ")]] public string e-mail {get; SeT ///<summary>///Security issues///</summary> [Display (name= "secret security Issue", description= "please fill in correctly, when you forget the password, the user retrieve the password." 4-20 characters. ")] [Required (errormessage =" x ")] [Stringlength (minimumlength = 4, errormessage =" x ")] public string securityques
 tion {get; set;} <summary>///Secret Answer///</summary> [Display (name= "Secret Answer", description= "please fill in carefully, forget the password after the correct answer to retrieve the password." 2-20 characters. ")] [Required (errormessage =" x ")] [Stringlength (minimumlength = 2, errormessage =" x ")] public string SECURITYANSW
 er {get; set;} <summary>///QQ number///</summary> [Display (name= "QQ number")] [RegularExpression ("^[1-9][0-9]{4-13]$", Erro
 Rmessage = "x")] [Stringlength (minimumlength = 6, errormessage = "x")]] public string QQ {get; set;} <summary>///Phone number///</summary> [Display (name= "phone number", description= "commonly used contact telephone (cell phone or landline), the fixed line format is: Area code-number. ")] [RegularExpression (" ^[0-9-]{11-13}$ ", errormessage =" x ")]] public string Tel {get; Set ///<summary>///Contact Address///</summary> [Display (name= "Contact address", description= "common address, up to 80 characters.") ] [Stringlength (errormessage = "x")] public string address {get; Set  ///<summary>///zip///</summary> [Display (name= "zip")] [RegularExpression ("^[0-9]{6}$", errormessage =
 ' X ']] public string postcode {get; set;} <summary>///Registration Time///</summary> public DateTime?
 regtime {get; set;} <summary>///last logon time///</summary> public DateTime?

 lastlogintime {get; set;}
 <summary>///User Group///</summary> public virtual usergroup Group {get; set;} 

 }

Add user controller below. Right-click in the Controller folder to select the new controller name input Usercontroller, when completed, generate the following code:

Using SYSTEM.WEB.MVC;
Using CMS. Models;

Namespace CMS. Controllers
{public
 class Usercontroller:controller
 {public

 actionresult Register ()
 {
 return View ();
 }
 //POST:/user/create

 [httppost] public
 actionresult Register (userregister uerreg)
 {
 Try
 {
 //Todo:add insert logic here return

 redirecttoaction ("Index");
 }
 Catch
 {return
 View ();
 }
 }}
 

Immediately involved in the problem is the data access, was intended to do with the repository mode, and later felt that the use of repository mode in a person to write a simple Web site is not meaningful, write a bit verbose, simply using pseudo-repository mode to write. New repository folder in the project. Create a new class CMS in the folder to implement the EF context. The code is as follows:

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;
Using System.Data.Entity;
Using CMS. Models;

Namespace CMS. Repository
{public
 class Cmscontext:dbcontext
 {public
 dbset<user> the Users {get; set;}
 }
} 

It's easy. Then build a class repositorybase, used to do ***repository base class, which write add,update,delete,find several virtual functions, convenient in the inheritance of these functions in the name of the unification.

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;

Namespace CMS. Repository
{public
 class repositorybase<tmodel>
 {
 private cmscontext dbcontext;
 Public Repositorybase ()
 {
 dbcontext = new CmsContext ();
 }
 <summary>
 ///Add "inheriting class overrides to normal use"
 ///</summary> public
 virtual bool Add (TModel TModel) { return false;
 ///<summary>
 ///Update "Inherit class overrides to work correctly"
 ///</summary> public
 virtual BOOL Update ( TModel TModel) {return false;}
 <summary>
 ///Delete "Inheriting class overrides to normal use"
 ///</summary> public
 virtual BOOL Delete (int Id) { return false;
 ///<summary>
 ///Find specified value "Inherit class overrides to normal use"
 ///</summary> public
 virtual TModel found ( int Id) {return default (TModel);}
 ~repositorybase ()
 {
 if (dbcontext!= null)
 {
 dbcontext.dispose ()
}}}} 

Can write the concrete implementation of Userrepository, new Userrepository class. The code after overriding the Add,update method is as follows:

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web; Using CMS.

Models; Namespace CMS.
 Repository {public class Userrepository:repositorybase<user> {private CmsContext dbcontext;
 Public Userrepository () {dbcontext = new CmsContext (); ///<summary>///Add user///</summary>///<param name= "user" > User information </param>///&LT;RETURNS&G
 t;</returns> public override bool Add (user user) {if (user = null) return false;
 DBCONTEXT.USERS.ADD (user);
 if (dbcontext.savechanges () > 0) return true;
 else return false; ///<summary>///Update user information///</summary>///<param name= "user" ></param>///<returns> </returns> public override bool Update (user user) {var _user = dbContext.Users.SingleOrDefault (u => u.userid = = user.
 USERID);
 if (_user = null) return false;
 _user = user;
 if (dbcontext.savechanges () > 0) return true;
 else return false; }//public Override}
} 

 

Here Repository The basic mode also came out, now MVC in the M and C have come out on the difference V, less v is the equivalent of high rich handsome less "rich" in high, again handsome are useless. Then get ready to write a view. &NBSP
@Html. Label can be used to show display (name= "") for a field, @Html. displaytext Displays the field values in the model. The HtmlHelper of display (..., description= "") property for displaying fields in the model was not found. Write one for yourself first. Create a new extensions folder in your project, right-click to add Class Displaydescriptionextensions, In the generated code, change the namespace to System.Web.Mvc.Html, adding two static methods Displaydescription and Displaydescriptionfor. After completion code &NBSP;:

Using System.Linq.Expressions;  namespace System.Web.Mvc.Html {public static class Displaydescriptionextensions {///<summary>///model description Information/// </summary>///<param name= "HtmlHelper" ></param>///<param name= "name" ></param>///
 ;returns></returns> public static mvchtmlstring displaydescription (This htmlhelper htmlhelper, string name) {
 Modelmetadata _modelmetadata = modelmetadata.fromstringexpression (name, htmlhelper.viewdata);
 Return Mvchtmlstring.create (_modelmetadata.description); ///<summary>///Model description Information///</summary>///<typeparam name= "TModel" ></typeparam>///<t Ypeparam name= "TResult" ></typeparam>///<param name= "HtmlHelper" ></param>///<param "Name=" Expression "></param>///<returns></returns> public static mvchtmlstring Displaydescriptionfor <tmodel, tresult> (this htmlhelper<tmodel> htmlhelper, Expression<func<tmoDel, tresult>> expression) {Modelmetadata _modelmetadata = modelmetadata.fromlambdaexpression (expression,
 Htmlhelper.viewdata);
 Return Mvchtmlstring.create (_modelmetadata.description); 

 }
 }
}

OK, in view can directly use @html.displaydescriptionfor (model => model. UserName) or @html.displaydescription (". UserName ") invokes the descriptive information.

Arrived here, roughly the preparation work almost, there are two small dongdong realize can write specific function.

First small Dongdong: verification Code . The verification code is divided into two pieces, one is to randomly obtain a certain number of digits of the character, the other is to draw the characters into the picture.

Add the common folder to the project, create a new text class in the folder, Verificationtext the class implementation function () use random to get the random string of the specified length, and then write the code:

 using System; Namespace CMS.
 Common {///<summary>///text related///</summary> public class Text {///<summary>///get Authenticode "string"
 </summary>///<param name= "Length" > Verification code Length "must be greater than 0" </param>///<returns></returns>
 public static string Verificationtext (int Length) {char[] _verification = new Char[length];
 Random _random = new Random ();  Char[] _dictionary = {' A ', ' B ', ' C ', ' D ', ' E ', ' F ', ' G ', ' H ', ' I ', ' J ', ' K ', ' L ', ' M ', ' N ', ' O ', ' P ', ' Q ', ' R ', ' S ', ' T ', ' U ', ' V ', ' W ', ' X ', ' Y ', ' Z ', ' A ', ' B ', ' C ', ' d ', ' e ', ' f ', ' g ', ' h ', ' I ', ' j ', ' K ', ' l ', ' m ', ' n ', ' o ', ' P ', ' Q ', ' R ', '
 S ', ' t ', ' u ', ' V ', ' w ', ' x ', ' y ', ' z ', ' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 '}; for (int i = 0; i < Length; i++) {_verification[i] = _dictionary[_random. Next (_dictionary.
 LENGTH-1)];
 Return to new String (_verification); }
 }
} 

Now you can draw the verification code, which uses the. NET GDI +, I read a lot of friends to write the verification code, generally draw a lot of interference points and interference lines, the purpose is to make the verification code is not easy to computer, personally feel that the drawing of the word when the material brush should also be able to achieve the purpose, so found a watercolor painting material.

Use this to do the word of the material should not be easy to identify it, start to write the drawing code, in the Usercontroller to create a new action called Verificationcode, the code is as follows:

<summary>///Draw Verification Code///</summary>///<returns></returns> public ActionResult Verificati
 Oncode () {int _verificationlength = 6;
 int _width = m, _height = 20;
 SizeF _verificationtextsize;
 Bitmap _bitmap = new Bitmap (Server.MapPath ("~/skins/common/texture.jpg"), true);
 TextureBrush _brush = new TextureBrush (_BITMAP);
 Gets the authentication code string _verificationtext = Common.Text.VerificationText (_verificationlength);
 Storage authentication Code session["Verificationcode"] = _verificationtext.toupper ();
 Font _font = new Font ("Arial", fontstyle.bold);
 Bitmap _image = new Bitmap (_width, _height);
 Graphics _g = Graphics.fromimage (_image);
 Clear background color _g.clear (color.white);
 Draw Verification Code _verificationtextsize = _g.measurestring (_verificationtext, _font); _g.drawstring (_verificationtext,_font,_brush, (_width-_verificationtextsize.width)/2, (_height-_
 Verificationtextsize.height)/2); _image.
 Save (Response.outputstream, System.Drawing.Imaging.ImageFormat.Jpeg);
 return null; 

 }

Open the browser and see the effect is good. To complete the preparation work.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.