asp.net MVC5 website Development user modification information and password (vi) _ Practical skills

Source: Internet
Author: User

In the last Article Web development (v) to achieve the user's cancellation and login, in fact, the code dropped something, is the user login to update the last logon time and login IP, this time up. Today to make changes to the data and modify the password, TryUpdateModel is a new use of things.

Now perfect yesterday's login code:

First, the User navigation menu
This is the sidebar navigation, then all the controllers in the action name is menu. The target effect is as follows:

Usercontroller Add menu action first. Returns the distribution view directly. Right-click to add a view

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

Second, display user information
Then add the action details that display the user data to the users controller. Later agreed to all display details of the action names for details. Returns the current user's data in the controller

<summary>
 ///Display data
 ///</summary>
 ///<returns></returns>
 Public ActionResult Details ()
 {return
  View (Userservice.find (User.Identity.Name));
 }

Right-click to add a view

@model Ninesky.Models.User @{viewbag.title = "My Information";} &lt;div class= "Row" &gt; &lt;div class= "col-md-3 col-sm-4" &gt; @Html. Action ("menu") &lt;/div&gt; &lt;div class= " Col-md-9 col-sm-8 "&gt; &lt;ol class=" breadcrumb "&gt; &lt;li&gt;&lt;span class=" Glyphicon glyphicon-home "&gt;&lt;a &gt; Member Center &lt;/a&gt;&lt;/span&gt;&lt;/li&gt; &lt;li&gt;&lt;a&gt; Personal Center &lt;/a&gt;&lt;/li&gt; &lt;li&gt; Modify Data &lt;/li &gt; &lt;/ol&gt; @using (Html.BeginForm ("Modify", "User")) {@Html. AntiForgeryToken () &lt;div class= "Form-horizont Al "&gt; &lt;h4&gt; user Information &lt;/h4&gt; &lt;hr/&gt; @Html. ValidationSummary (True) @Html. Hiddenfor (model =&gt; model. UserID) &lt;div class= "Form-group" &gt; @Html. Labelfor (model =&gt; model. UserName, new {@class = "Control-label col-md-2"}) &lt;div class= "col-md-10" &gt; @Html. Displayfor (Model =&gt; mode L.username) &lt;/div&gt; &lt;/div&gt; &lt;div class= "Form-group" &gt; @Html. Labelfor (model =&gt; model. DisplayName, new {@class = "Control-labelCol-md-2 "}" &lt;div class= "col-md-10" &gt; @Html. Editorfor (model =&gt; model. DisplayName) @Html. Validationmessagefor (model =&gt; model. DisplayName) &lt;/div&gt; &lt;/div&gt; &lt;div class= "Form-group" &gt; &lt;label class = "Control-label col-md-2 "&gt; User group &lt;/label&gt; &lt;div class=" col-md-10 "&gt; @foreach (var _relation in model.userrolerelations) {&LT;SPAN&G T;@_relation. Role.name&lt;/span&gt;&lt;br/&gt} &lt;/div&gt; &lt;/div&gt; &lt;div class= "Form-group" &gt; @Html. Labelfor (mod El =&gt; model. Email, new {@class = "Control-label col-md-2"}) &lt;div class= "col-md-10" &gt; @Html. Editorfor (model =&gt; model. Email) @Html. Validationmessagefor (model =&gt; model.
   Email) &lt;/div&gt; &lt;/div&gt; &lt;div class= "Form-group" &gt; &lt;div class= "col-md-offset-2 col-md-10" &gt; &lt;input type= "Submit" value= "Modify" class= "btn btn-default"/&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;} &lt;/d Iv&gt; &lt;/div&gt; @section Scripts {@ScRipts. Render ("~/bundles/jqueryval")}

@foreach (
var _relation in model.userrolerelations) {<span>@_relation. Role.name</span><br/>} Here is the display user group name, deferred loading.

Third, modify user information
after displaying the user data, click Modify to submit the data directly to the background, here to accept and update the database action name is details. In this method can not directly use user to do method parameters, because I just want to follow the new display name and mailbox, I set the user type of parameters, if the user submitted to the server contains username, may be the user name will be changed, here use TryUpdateModel to partially update the model.

<summary>
 ///Modification 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 information needed to be modified")
   ;
  }
  else Modelstate.addmodelerror ("", "Update model data failed");
  }
  Return View ("Details", _user);
 }

TryUpdateModel in the code (_user, new string[] {"DisplayName", "Email"}) indicates that I only want to update DisplayName and email from the data submitted by the customer

Four, modify the password
Create a view model first Changepasswordviewmodel

Using System.ComponentModel.DataAnnotations; namespace Ninesky.Web.Areas.Member.Models {///&lt;summary&gt;///Modify password view model///&lt;remarks&gt; Create: 2014.02.19&lt;/rema 
 Rks&gt;///&lt;/summary&gt; public class Changepasswordviewmodel {///&lt;summary&gt;///original password///&lt;/summary&gt;
 [Required (errormessage = "required")]
 [Display (Name = "password")]
 [Stringlength (minimumlength = 6, errormessage = "{2} to {1} characters")]

 [DataType (Datatype.password)] public string Originalpassword {get; set;} &lt;summary&gt;///New Password///&lt;/summary&gt; [Required (errormessage = "required")] [Display (Name = "New password")] [stringlengt H (minimumlength = 6, errormessage = "{2} to {1} characters")] [DataType (Datatype.password)] public string Password {get; set; ///&lt;summary&gt;///Confirm password///&lt;/summary&gt; [Required (errormessage = "required"]] [Compare ("Password", Errormessag
 E = "Two input passwords inconsistent")] [Display (Name = Confirm password)] [DataType (Datatype.password)] public string ConfirmPassword {get; set;} }
}

The action public ActionResult ChangePassword () is then added to the Usercontroller to directly return to a view. Right-click to add Changepasswordviewmodel type view

@model Ninesky.Web.Areas.Member.Models.ChangePasswordViewModel @{viewbag.title = "Modify password";} &lt;div class= "row" &gt; &L T;div class= "col-md-3 col-sm-4" &gt; @Html. Action ("menu") &lt;/div&gt; &lt;div class= "col-md-9 col-sm-8" &gt; &lt;ol class= "breadcrumb" &gt; &lt;li&gt;&lt;span class= "Glyphicon glyphicon-home" &gt;&lt;a&gt; Member Center &lt;/a&gt;&lt;/span &gt;&lt;/li&gt; &lt;li&gt;&lt;a&gt; Personal Center &lt;/a&gt;&lt;/li&gt; &lt;li&gt; Modify Password &lt;/li&gt; &lt;/ol&gt; @using (html.be 
  Ginform ()) {@Html. AntiForgeryToken () &lt;div class= "Form-horizontal" &gt; &lt;h4&gt; modify password &lt;/h4&gt; &lt;hr/&gt; @Html. ValidationSummary (True) &lt;div class= "Form-group" &gt; @Html. Labelfor (model =&gt; model. Originalpassword, new {@class = "Control-label col-md-2"}) &lt;div class= "col-md-10" &gt; @Html. Editorfor (Model =&G T Model. Originalpassword) @Html. Validationmessagefor (model =&gt; model. Originalpassword) &lt;/div&gt; &lt;/div&gt; &lt;div class= "Form-group" &gt; @Html. Labelfor (model =&gt; model. Password, new {@class = "Control-label col-md-2"}) &lt;div class= "col-md-10" &gt; @Html. Editorfor (Model =&gt; model . Password) @Html. Validationmessagefor (model =&gt; model. Password) &lt;/div&gt; &lt;/div&gt; &lt;div class= "Form-group" &gt; @Html. Labelfor (model =&gt; model. ConfirmPassword, new {@class = "Control-label col-md-2"}) &lt;div class= "col-md-10" &gt; @Html. Editorfor (Model =&gt ; Model. ConfirmPassword) @Html. Validationmessagefor (model =&gt; model. ConfirmPassword) &lt;/div&gt; &lt;/div&gt; &lt;div class= "Form-group" &gt; &lt;div class= "col-md-offset-2 COL-MD 
 -10 "&gt; &lt;input type=" Submit "value=" Modified "class=" btn btn-default "/&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; } @section Scripts {@Scripts. Render ("~/bundles/jqueryval")} &lt;/div&gt; &lt;/div&gt;

The code is simple when you add an accept-processing 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 ("", "Modify password successful");
   else Modelstate.addmodelerror ("", "Modify password Failed");
  }
  else Modelstate.addmodelerror ("", "Original password error");
  }
  Return View (Passwordviewmodel);
 }

Five, on the first page display login, registration link
Add the loginpartial.cshtml view file to the shared file in the Web, display the login and registration link when the user is not logged in, and display the user name after the login.

@using Microsoft.AspNet.Identity
@if (request.isauthenticated)
{
 using (Html.BeginForm ("Logout", "User ", FormMethod.Post, new {id =" Logoutform ", @class =" Navbar-right "}))
 {
 @Html. AntiForgeryToken ()

 <ul cl ass= "Nav navbar-nav navbar-right" >
  <li>
  @Html actionlink ("Hello" + User.Identity.GetUserName () + "!", " Manage ", Account", Routevalues:null, htmlattributes:new {title = "Admin"})
  </li>
  <li><a href= "J Avascript:document.getElementById (' Logoutform '). Submit () "> Logout </a></li>
 </ul>
 }"
}
else
{
 <ul class= "nav navbar-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 logging in

After landing

Ok. Now we can add [authorize] attributes to the Usercontroller controller and HomeController for the member area. and the [allowanonymous] attribute is added to the Usercontroller registration login Verification Code action.

The modified data section uses a partial update model method TryUpdateModel to temporarily end the user portion of this member area. The next start content, I hope you continue to pay attention.

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.