Background Management of user roles for ASP. NET MVC5 website development 1 (7) and mvc5 website development
A role is a function available in the website to differentiate user types and divide user permissions. This operation allows you to browse the role list, add roles, modify roles, and delete roles.
I. business logic layer
1. Role Model
Ninesky. Core right-click and choose "add"> "class". Enter the class name "Role.
Reference the System. ComponentModel. DataAnnotations namespace
Using System. componentModel. dataAnnotations; namespace Ninesky. core {// <summary> /// Role /// </summary> public class Role {[Key] public int RoleID {get; set ;} /// <summary> /// name /// </summary> [Required (ErrorMessage = "{0}" Required)] [StringLength (20, MinimumLength = 2, errorMessage = "{0} is {2}-{1} characters")] [Display (Name = "Name")] public string Name {get; set ;} /// <summary> /// description /// </summary> [StringLength (1000, ErrorMessage = "{0} must be less than {1} characters")] [Display (Name = "Description")] public string Description {get; set ;}}}
2. Add Table ing
Open Ninesky. Core/NineskyContext. cs and add Role table ing
3. Data Migration
1) Enable data migration
In the toolbar, choose tools> NuGet Package Manager> Package Manager Console.
Enter the Enable-Migrations command and press enter to Enable data migration for Ninesk. Core.
Open the Ninesky. Core/Migrations/Configuration. cs File
Set AutomaticMigrationsEnabled = false; To AutomaticMigrationsEnabled = ture; to enable automatic migration.
2) update the data table
Run the Update-Database command. Error message: There is already an object named 'administrators 'in the database.
This is because data migration is enabled after the Administrator table is created. An error occurred while creating the Administrators table in the view when updating the table.
Open the server resource manager and choose Administrators [Right-click]> Delete.
After the deletion is successful, run Update-Database again. The operation is successful.
Because the Administrator account was deleted when the table was deleted, remember to open the Administrators table and add an administrator account. Remember to enter the jZae727K08KaOmKSgOaGzww/XVqGr/PKEgIMkjrcbJI = This is the 123456 encrypted string.
4. role management
Ninesky. Core [Right-click]-> Add-> class, enter the class name RoleManager, and the class inherits from BaseManager <Role>
Using System; using System. collections. generic; using System. linq; using System. text; using System. threading. tasks; namespace Ninesky. core {/// <summary> /// Role management /// </summary> public class RoleManager: BaseManager <Role> {}}
Ii. Presentation Layer
Ninesky. Web/Areas/Control/Controllers [Right-click]-> Add-> controller. Select MVC5 controller-null and enter the Controller name RoleController.
Introduce namespace in the ControllerNinesky. Core;
Add variablePrivate RoleManager roleManager = new RoleManager ();
Add authentication [AdminAuthorize] to the Controller
1. Message prompt
When performing an operation, you often need to Prompt the operation for success, failure, and error. Therefore, a Prompt model class Prompt is specially designed.
1) Add a class
Ninesky. Web/Models [Right-click]-> Add-> class input class name Prompt
Copy codeThe Code is as follows: using System. collections. generic; namespace Ninesky. web. models {/// <summary> /// Prompt /// </summary> public class Prompt {/// <summary> /// title /// </summary> public string Title {get; set ;}//< summary >/// Message //</summary> public string Message {get; set ;} /// <summary >/// button group /// </summary> public List <string> Buttons {get; set ;}}}
2. Introduce the class namespace in the Controller
REFERENCE The namespace Ninesky. Web. Models in Rolecontroller.
3. Add a view
In Ninesky. Web/Areas/Control/Views/Shared [Right-click]-> Add-> View
@ Model Ninesky. web. models. prompt @ {ViewBag. title = Model. title;} @ section SideNav {@ Html. partial ("SideNavPartialView")} <ol class = "breadcrumb"> <li> <span class = "glyphicon-home"> </span> @ Html. actionLink ("Homepage", "Index", "Home") </li> <li class = "active"> @ Model. title </li> </ol> <div class = "panel-default"> <div class = "panel-heading"> <div class = "panel-title"> @ Model. title </div> <div class =" Panel-body "> <p> @ Html. Raw (Model. Message) </p> @ if (Model. Buttons! = Null & Model. buttons. count> 0) {<p> @ foreach (var item in Model. buttons) {@ Html. raw (item + "") }</p >}</div> </div>
2. Administrator list
1) return list method (in Json format)
Add the method ListJson () to the control and return the type JsonResoult.
/// <Summary> /// list [Json] /// </summary> /// <returns> </returns> public JsonResult ListJson () {return Json (roleManager. findList ());}
2. Add the role homepage View
Right-click the index () method and choose "add view ".
@ {ViewBag. title = "role management";} @ section SideNav {@ Html. partial ("SideNavPartialView")} <ol class = "breadcrumb"> <li> <span class = "glyphicon-home"> </span> @ Html. actionLink ("Homepage", "Index", "Home") </li> <li> @ Html. actionLink ("User Management", "Index", "User") </li> <li class = "active"> @ Html. actionLink ("Role management", "Index", "Role ") </li> </ol> <table id = "admingrid"> </table> @ section style {@ Styles. render ("~ /Content/bootstrapplugincss ")} @ section scripts {@ Scripts. Render ("~ /Bundles/jqueryval ") @ Scripts. Render ("~ /Bundles/bootstrapplugin ") <script type =" text/javascript ">$ (document ). ready (function () {// table var $ table =$ ('# admingrid'); $ table. bootstrapTable ({showRefresh: true, showColumns: true, showFooter: true, method: "post", url: "@ Url. action ("ListJson") ", columns: [{title:" ID ", field:" RoleID "},{ title:" Name ", field:" Name ", formatter: function (value, row, index) {return "<a href = '@ Url. action (" Modify "," Role ")/" + row. roleID + "'>" + value + "</a>" }}, {title: "Description", field: "Description" },{ title: "operation ", field: "RoleID", formatter: function (value) {return "<a class = 'btn btn-sm btn-danger 'data-operation = 'delimiterole' data-value = '" + value + "'> Delete </a> "}], onLoadSuccess: function () {// delete button $ ("a [data-operation = 'deleterole']"). click (function () {var id = $ (this ). attr ("data-value "); BootstrapDialog. confirm ("are you sure you want to delete" + $ (this ). parent (). parent (). find ("td "). eq (1 ). text () +? ", Function (result) {if (result) {$. post ("@ Url. action ("DeleteJson", "Role") ", {id: id}, function (data) {if (data. code = 1) {BootstrapDialog. show ({message: "role deleted successfully", buttons: [{icon: "glyphicon-OK", label: "OK", action: function (dialogItself) {$ table. bootstrapTable ("refresh"); dialogItself. close () ;}}]});} else BootstrapDialog. alert (data. message) ;}, "json") ;}}) ;}; // The End Of The delete button }}); // the end of the table}); </script>}
3. Navigation View
The navigation view is displayed on the left of the view. You can navigate the functions of the controller.
Ninesky. Web/Areas/Control/Views/Role [Right-click]-> Add-> View
<Div class = "panel-default"> <div class = "panel-heading"> <div class = "panel-title"> <span class = "glyphicon-user "> </span> User management </div> <div class =" panel-body "> <div class =" list-group "> <div class = "list-group-item"> <span class = "glyphicon-plus"> </span> @ Html. actionLink ("Add Role", "Add", "Role ") </div> <div class = "list-group-item"> <span class = "glyphicon-list"> </span> @ Html. actionLink ("Role management", "Index", "Role") </div>
4. Add a role
1) Add Methods
Add the Add method to the Controller
Copy codeThe Code is as follows: // <summary> /// Add /// </summary> /// <returns> </returns> public ActionResult Add () {return View ();}
2) Add a view
Right-click a method to add a view
@ Model Ninesky. core. role @ {ViewBag. title = "add role";} @ section SideNav {@ Html. partial ("SideNavPartialView")} <ol class = "breadcrumb"> <li> <span class = "glyphicon-home"> </span> @ Html. actionLink ("Homepage", "Index", "Home") </li> <li> @ Html. actionLink ("User Management", "Index", "User") </li> <li> @ Html. actionLink ("Role management", "Index", "Role ") </li> <li class = "active"> Add a role </li> </ol> @ using (Html. beginForm () {@ Html. antiForg EryToken () <div class = "form-horizontal"> @ Html. validationSummary (true, "", new {@ class = "text-danger"}) <div class = "form-group"> @ Html. labelFor (model => model. name, htmlAttributes: new {@ class = "control-label col-md-2"}) <div class = "col-md-10"> @ Html. editorFor (model => model. name, new {htmlAttributes = new {@ class = "form-control"}) @ Html. validationMessageFor (model => model. name, "", ne W {@ class = "text-danger"}) </div> <div class = "form-group"> @ Html. labelFor (model => model. description, htmlAttributes: new {@ class = "control-label col-md-2"}) <div class = "col-md-10"> @ Html. editorFor (model => model. description, new {htmlAttributes = new {@ class = "form-control"}) @ Html. validationMessageFor (model => model. description, "", new {@ class = "text-danger"}) </div> </div> <Div class = "form-group"> <div class = "col-md-offset-2 col-md-10"> <input type = "submit" value = "save" class = "btn-default" /> </div>} @ section Scripts {@ Scripts. render ("~ /Bundles/jqueryval ")}
3) add methods for receiving and processing submitted data
Add the post method of the Add method to the Controller
[HttpPost] [ValidateAntiForgeryToken] public ActionResult Add (Role role) {if (ModelState. isValid) {if (roleManager. add (role ). code = 1) {return View ("Prompt", new Prompt () {Title = "added successfully", Message = "you have successfully added the role [" + role. name + "]", Buttons = new List <string> () {"<a href = \" "+ Url. action ("Index", "Role") + "\" class = \ "btn-default \"> Role management </a> ", "<a href = \" "+ Url. action ("Add", "Role") + "\" class = \ "btn-default \"> Add more </a> "}});}} return View (role );}
5. Administrator data modification
1) Add Methods
Add in ControllerModifyMethod.
/// <Summary> /// modify /// </summary> /// <param name = "id"> RoleID </param> /// <returns> </returns> public ActionResult Modify (int id) {var _ role = roleManager. find (id); if (_ role = null) return View ("Prompt", new Prompt () {Title = "error ", message = "the role with ID [" + id + "] does not exist", Buttons = new List <string> () {"<a href = \" "+ Url. action ("Index", "Role") + "\" class = \ "btn-default \"> Role management </a> "}}); return View (_ role );}
2) Add a view
Right-click a method to add a view
The Code is as follows:
@ Model Ninesky. core. role @ {ViewBag. title = Model. name ;}@ section SideNav {@ Html. partial ("SideNavPartialView")} <ol class = "breadcrumb"> <li> <span class = "glyphicon-home"> </span> @ Html. actionLink ("Homepage", "Index", "Home") </li> <li> @ Html. actionLink ("User Management", "Index", "User") </li> <li> @ Html. actionLink ("Role management", "Index", "Role ") </li> <li class = "active"> modify </li> </ol> @ using (Html. beginForm () {@ Html. antiFor GeryToken () <div class = "form-horizontal"> @ Html. validationSummary (true, "", new {@ class = "text-danger"}) @ Html. hiddenFor (model => model. roleID) <div class = "form-group"> @ Html. labelFor (model => model. name, htmlAttributes: new {@ class = "control-label col-md-2"}) <div class = "col-md-10"> @ Html. editorFor (model => model. name, new {htmlAttributes = new {@ class = "form-control"}) @ Html. validati OnMessageFor (model => model. name, "", new {@ class = "text-danger"}) </div> <div class = "form-group"> @ Html. labelFor (model => model. description, htmlAttributes: new {@ class = "control-label col-md-2"}) <div class = "col-md-10"> @ Html. editorFor (model => model. description, new {htmlAttributes = new {@ class = "form-control"}) @ Html. validationMessageFor (model => model. description, "", new {@ Class = "text-danger "}) </div> <div class = "form-group"> <div class = "col-md-offset-2 col-md-10"> <input type = "submit" value = "save" class = "btn-default"/> </div >}@ section Scripts {@ Scripts. render ("~ /Bundles/jqueryval ")}
3) add methods for receiving and processing submitted data
Add the post method to the Controller for submission.ModifyMethod.
[HttpPost] [ValidateAntiForgeryToken] public ActionResult Modify (Role role) {if (ModelState. isValid) {var _ resp = roleManager. update (role); if (_ resp. code = 1) return View ("Prompt", new Prompt () {Title = "successfully modified the role", Message = "you have successfully modified the role [" + role. name + "]", Buttons = new List <string> () {"<a href = \" "+ Url. action ("Index", "Role") + "\" class = \ "btn-default \"> Role management </a> ", "<a href = \" "+ Url. action ("Modify", "Role", new {id = role. roleID}) + "\" class = \ "btn-default \"> View </a> "," <a href = \ "" + Url. action ("Add", "Role") + "\" class = \ "btn-default \"> Add </a> "}}); else return View ("Prompt", new Prompt () {Title = "failed to modify role", Message = "cause of failure:" + _ resp. message, Buttons = new List <string> () {"<a href = \" "+ Url. action ("Index", "Role") + "\" class = \ "btn-default \"> Role management </a> ", "<a href = \" "+ Url. action ("Modify", "Role", new {id = role. roleID}) + "\" class = \ "btn-default \"> return </a> "});} else return View (role );}
6. delete a role
Add in ControllerModifyMethod.
/// <Summary> /// Delete [Json] /// </summary> /// <param name = "id"> RoleID </param> // <returns> </returns> [HttpPost] public JsonResult DeleteJson (int id) {return Json (roleManager. delete (id ));}
After the role function is completed, press F5 to preview the effect in the browser.
Bytes ---------------------------------------------------------------------------------------
See: https://ninesky.codeplex.com/SourceControl/latest for code
CODE Download: https://ninesky.codeplex.com click source code click Download to Download the SOURCE file.
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.