ASP. NET MVC5 website development users modify materials and passwords (6), mvc5 website development

Source: Internet
Author: User
Tags actionlink

ASP. NET MVC5 website development users modify materials and passwords (6), mvc5 website development

In the previous article website development (5), users are logged out and logged on. In fact, there is something in the code, that is, the last logon time and IP address must be updated during user logon, this time. Today, I want to modify materials and passwords. TryUpdateModel is a new application.

Now we have improved yesterday's logon code:

I. user navigation menu
This is the navigation of the sidebar. In the future, all action names in the Controller will be Menu. The target effect is as follows:

Add Menu action to UserController first. Directly return to the distribution view. Right-click to add view

<Div class = "panel-primary"> <div class = "panel-heading"> 

Ii. Display User Information
Add the action Details that displays User data in the User controller. In the future, it will be agreed that all the action names for displaying Details will be Details. Return the information of the current user in the controller.

/// <Summary> // display information /// </summary> /// <returns> </returns> public ActionResult Details () {return View (userService. find (User. identity. name ));}

Right-click to add view

@ Model Ninesky. models. user @ {ViewBag. title = "My Documents";} <div class = "row"> <div class = "col-md-3 col-sm-4"> @ Html. action ("Menu ") </div> <div class = "col-md-9 col-sm-8"> <ol class = "breadcrumb"> <li> <span class = "glyphicon-home"> <a> member center </a> </span> </li> <a> personal center </a> </li> <li> modify Information </li> </ol> @ using (Html. beginForm ("Modify", "User") {@ Html. antiForgeryToken () <div class = "form-horizontal"> 

@ Foreach (
Var _ relation in Model. UserRoleRelations) {<span> @ _ relation. Role. Name </span> <br/>} the Name of the user group is displayed, delaying loading.

 3. Modify user information
After the user information is displayed, click Modify to submit data directly to the background. Here, the action name for accepting and updating the database is also Details. In this method, User cannot be used as the method parameter directly, because I only want to follow the new display name and mailbox. If I set User-type parameters, if the parameters submitted by the User to the server contain UserName, the user name may be changed. Here we use TryUpdateModel to partially update the model.

/// <Summary> // Modify the data // </summary> /// <returns> </returns> [ValidateAntiForgeryToken] [HttpPost] public ActionResult Modify () {var _ user = userService. find (User. identity. name); if (_ user = null) ModelState. addModelError ("", "user does not exist"); else {if (TryUpdateModel (_ user, new string [] {"DisplayName", "Email"}) {if (ModelState. isValid) {if (userService. update (_ user) ModelState. addModelError ("", "Modified successfully! "); Else ModelState. addModelError ("", "No materials to be modified") ;}} else ModelState. addModelError ("", "failed to update model data");} return View ("Details", _ user );}

In the code, TryUpdateModel (_ user, new string [] {"DisplayName", "Email"}) indicates that I only want to update DisplayName and Email from the data submitted by the customer.
 
4. Change the password
Create a view model ChangePasswordViewModel first

Using System. componentModel. dataAnnotations; namespace Ninesky. web. areas. member. models {/// <summary> /// modify the password View model /// <remarks> Create: 2014.02.19 </remarks> /// </summary> public class ChangePasswordViewModel {// <summary> // original password /// </summary> [Required (ErrorMessage =" required ")] [Display (Name = "password")] [StringLength (20, MinimumLength = 6, ErrorMessage = "{2} to {1} characters")] [DataType (DataType. password)] public string OriginalPassword {get; set ;} /// <summary> // new password /// </summary> [Required (ErrorMessage = "Required")] [Display (Name = "new password")] [StringLength (20, MinimumLength = 6, ErrorMessage = "{2} to {1} characters")] [DataType (DataType. password)] public string Password {get; set ;} /// <summary> /// confirm the Password /// </summary> [Required (ErrorMessage = "Required")] [Compare ("Password ", errorMessage = "inconsistent passwords entered twice")] [Display (Name = "Confirm Password")] [DataType (DataType. password)] public string ConfirmPassword {get; set ;}}}

Then, add the public ActionResult ChangePassword () Action to UserController to return to a view. Right-click ChangePasswordViewModel to add a view

@ Model Ninesky. web. areas. member. models. changePasswordViewModel @ {ViewBag. title = "Change Password";} <div class = "row"> <div class = "col-md-3 col-sm-4"> @ Html. action ("Menu ") </div> <div class = "col-md-9 col-sm-8"> <ol class = "breadcrumb"> <li> <span class = "glyphicon-home"> <a> member center </a> </span> </li> <a> personal center </a> </li> <li> Change Password </li> </ol> @ using (Html. beginForm () {@ Html. antiForgeryToken () <div class = "form- Horizontal "> 

The Code is also very simple when you add an accept action

[ValidateAntiForgeryToken] [HttpPost] public ActionResult ChangePassword (ChangePasswordViewModel passwordViewModel) {if (ModelState. isValid) {var _ user = userService. find (User. identity. name); if (_ user. password = Common. security. sha256 (passwordViewModel. originalPassword) {_ user. password = Common. security. sha256 (passwordViewModel. password); if (userService. update (_ user) ModelState. addModelError ("", "password modified"); else ModelState. addModelError ("", "failed to Change Password");} else ModelState. addModelError ("", "Incorrect original password");} return View (passwordViewModel );}

5. the logon and registration links are displayed on the homepage.
Add the LoginPartial. cshtml view file to the Web Shared file. The logon and registration links are displayed when the user is not logged on, and the user name is displayed after logon.

@ Using Microsoft. aspNet. identity @ if (Request. isAuthenticated) {using (Html. beginForm ("Logout", "User", FormMethod. post, new {id = "logoutForm", @ class = "navbar-right"}) {@ Html. antiForgeryToken () <ul class = "nav navbar-right"> <li> @ Html. actionLink ("hello" + User. identity. getUserName () + "! "," Manage "," Account ", routeValues: null, htmlAttributes: new {title =" "}) </li> <a href =" javascript: document. getElementById ('logoutform '). submit () "> logout </a> </li> </ul >}} else {<ul class =" nav navbar-right "> <li> @ Html. actionLink ("Register", "Register", "User", routeValues: new {Area = "Member"}, htmlAttributes: new {id = "registerLink "}) </li> <li> @ Html. actionLink ("Login", "Login", "User", routeValues: new {Area = "Member"}, htmlAttributes: new {id = "loginLink "}) </li> </ul>}

The effect is as follows:

Before Login

After Login

OK. Now we can add the [Authorize] feature to the UserController controller and Homecontroller in the member region. Add the [AllowAnonymous] feature to the registered logon Verification Code action of Usercontroller.

Part of the modified materials used part of the updated model method TryUpdateModel. The user part of this member region is now complete. I hope you will continue to pay attention to the content next time.

Related Article

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.