Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the functions of the administrator in the development of ASP.NETMVC5 website

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article will explain in detail about the functions of administrators in ASP.NETMVC5 website development, and the content of the article is of high quality, so the editor will share it with you for reference. I hope you will have a certain understanding of the relevant knowledge after reading this article.

First, install plug-ins.

The front-end framework of the presentation layer is mainly Bootstrap, because the js function of Bootstrap is weak, so some plug-ins are added here. In fact, many js plug-ins can be installed through NuGet, but NuGet installation adds more content, not as clean as their own copy, so all the plug-ins here are downloaded and copied to the project.

1 、 Bootstrap 3 Datepicker 4.17.37

Web site: https://eonasdan.github.io/bootstrap-datetimepicker/

Download and extract the package-> copy bootstrap-datetimepicker.js and bootstrap-datetimepicker.min.js to the Scripts folder of the Ninesy.Web project, and copy bootstrap-datetimepicker.css and bootstrap-datetimepicker.min.css to the Content folder.

2 、 bootstrap-dialog 3.3.4.1

Web site: https://github.com/nakupanda/bootstrap3-dialog

Download and extract the package-> copy .js to the Scripts folder of the Ninesy.Web project, and copy .css to the Content folder.

3 、 bootstrap-select 1.10.0

Web site: http://silviomoreto.github.io/bootstrap-select/

Download and extract the package-> copy bootstrap-select.js to the Scripts folder of the Ninesy.Web project, and rename defaults-zh_CN.js to bootstrap-select-zh_CN.js to the Scripts folder of the Ninesy.Web project, and copy bootstrap-select.css, bootstrap-select.css.map, and bootstrap-select.min.css to the Content folder.

4 、 bootstrap-table 1.10.1

Web site: http://bootstrap-table.wenzhixin.net.cn/

Download and extract the package-> copy bootstrap-table.js and bootstrap-table-zh-CN.js to the Scripts folder of the Ninesy.Web project, and copy bootstrap-table.css to the Content folder.

5 、 Bootstrap TreeView 1.2.0

Web site: https://github.com/jonmiles/bootstrap-treeview

Download and extract the package-> copy bootstrap-treeview.js to the Scripts folder of the Ninesy.Web project, and copy bootstrap-treeview.css to the Content folder.

6 、 twbs-pagination

Web site: http://esimakin.github.io/twbs-pagination/

Download and unzip the package-> copy jquery.twbsPagination.js and jquery.twbsPagination.min.js to the Scripts folder of the Ninesy.Web project.

7. Bind and compress js and css

Open Ninesky.Web- > App_Start- > BundleConfig.cs. Add the code in the red box.

Second, the method of obtaining ModelState error information

Some content in the project is submitted through the AJAX method. If the client does not verify it at the time of submission, the error message will be saved in the ModelState when the verification is carried out on the server. Here, you need to write a method to obtain the error message of ModelState so that it can be fed back to the client.

1. Ninesk.Web [right]-> add-> class, and enter the class name General.

Reference the namespaces using System.Web.Mvc and System.Text.

Add the static method GetModelErrorString (), which is used to get the error string of the model.

Using System.Linq;using System.Text;using System.Web.Mvc;namespace Ninesky.Web {/ generic class / public class General {/ get model status / public static string GetModelErrorString (ModelStateDictionary modelState) {StringBuilder _ sb = new StringBuilder (); var _ ErrorModelState = modelState.Where (m = > m.Value.Errors.Count () > 0) Foreach (var item in _ ErrorModelState) {foreach (var modelError in item.Value.Errors) {_ sb.AppendLine (modelError.ErrorMessage);}} return _ sb.ToString ();}

Third, improve the layout page

The last time I completed the administrator login, this time to carry out some functions after login, we should first enrich the background layout page.

Open Ninesky.Web/Areas/Control/Views/_Layout.cshtml. Turn it into the following code. Artists like their own scum, the specific process will not be written.

ViewBag.Title-system Management @ Styles.Render ("~ / Content//controlcss") @ RenderSection ("style", required: false) @ Scripts.Render ("~ / bundles/modernizr") @ Scripts.Render ("~ / bundles/jquery") @ Scripts.Render ("~ / bundles/bootstrap") @ RenderSection ("scripts", required: false) @ Html.ActionLink ("NINESKY system Management", "Index", "Home", new {area = "Control"}) New {@ class = "navbar-brand"}) user Management administrators column Settings Web site Settings @ Context.Session ["Accounts"] .ToString () exit @ RenderSection ("SideNav", false) @ RenderBody ()

©Ninesky v0.1 BASE BY Evening http://mzwhj.cnblogs.com

That's what it looks like anyway.

Third, function realization

As envisioned, the browsing, adding and deleting functions of the administrator should be completed in the Index interface. These functions are in ajax mode.

The Index () method is automatically added when you add AdminController.

Add an Index view

Right-click on the Index method to add a view

@ {ViewBag.Title = "administrator";} @ Html.ActionLink ("home page", "Index", "Home") @ Html.ActionLink ("administrator", "Index", "Admin") @ section style {@ Styles.Render ("~ / Content/bootstrapplugincss")} @ section scripts {@ Scripts.Render ("~ / bundles/jqueryval") @ Scripts.Render ("~ / bundles/bootstrapplugin")}

Add a sidebar navigation view

Ninesky.Web/Areas/Control/Views/Admin [right]-> add-> View

The view code is as follows

Administrator @ Html.ActionLink ("Administration", "Index")

Add @ section SideNav {@ Html.Partial ("SideNavPartialView")} in the Index view (see figure)

1. List of administrators

Add the ListJson () method to the Admin controller

/ list of administrators / public JsonResult ListJson () {return Json (adminManager.FindList ());}

To display and manipulate the list of administrators in index using bootstrap-table, add the following code to the index view.

Add and delete

Add js code to @ section scripts {}

$(document) .ready (function () {/ / form var $table = $('# admingrid') $table.bootstrapTable ({toolbar: "# toolbar", showRefresh: true, showColumns: true, showFooter: true, method: "post", url: "@ Url.Action (" ListJson ")", columns: [{title: "state", checkbox: true}, {title: "ID", field: "AdministratorID"}, {title: "account", field: "Accounts"}, {title: "login time", field: "LoginTime" Formatter: function (value) {return moment (value) .format ("YYYY-MM-DD HH:mm:ss")}, {title: "login IP", field: "LoginIP"}, {title: "creation time", field: "CreateTime", formatter: function (value) {return moment (value) .format ("YYYY-MM-DD HH:mm:ss")}, {title: "Action", field: "AdministratorID", formatter: function (value, row) Index) {return "reset password"}}]}) / / end of form});}

The display effect is as shown in the figure:

2. Add an administrator

Add the AddPartialView () method to the controller

/ / add [partial View] / public PartialViewResult AddPartialView () {return PartialView ();}

Models folder [right]-> add-> class, enter the class name AddAdminViewModel.

Using System.ComponentModel.DataAnnotations;namespace Ninesky.Web.Areas.Control.Models {/ add administrator model / public class AddAdminViewModel {/ account / [Required (ErrorMessage = "must enter {0}")] [StringLength (30, MinimumLength = 4, ErrorMessage = "{2}-{1} characters")] [Display (Name = "account")] public string Accounts {get; set } / password / [DataType (DataType.Password)] [Required (ErrorMessage = "must enter {0}")] [StringLength (20 minim length = 6, ErrorMessage = "{0} less than {1} characters")] [Display (Name = "password")] public string Password {get; set;}

Right-click to add view

Note: when grabbing the picture, you forget to tick the reference script library and catch it, remember to tick it.

@ model Ninesky.Web.Areas.Control.Models.AddAdminViewModel@using (Html.BeginForm ()) {@ Html.AntiForgeryToken () @ Html.ValidationSummary (true, ", new {@ class =" text-danger "}) @ Html.LabelFor (model = > model.Accounts, htmlAttributes: new {@ class =" control-label col-md-2 "}) @ Html.EditorFor (model = > model.Accounts New {htmlAttributes = new {@ class = "form-control"}) @ Html.ValidationMessageFor (model = > model.Accounts, ", new {@ class =" text-danger "}) @ Html.LabelFor (model = > model.Password, htmlAttributes: new {@ class =" control-label col-md-2 "}) @ Html.EditorFor (model = > model.Password, new {htmlAttributes = new {@ class =" form-control "}) @ Html.ValidationMessageFor (model = > model.Password," New {@ class = "text-danger"})} @ Scripts.Render ("~ / bundles/jqueryval")

In the script script area of the Index view, add js code after "/ / end of table"

/ / end of table / / toolbar / / add button $("# btn_add") .click (function () {var addDialog = new BootstrapDialog ({title: "add Administrator", message: function (dialog) {var $message = $(''); var pageToLoad = dialog.getData ('pageToLoad'); $message.load (pageToLoad); return $message) }, data: {'pageToLoad':' @ Url.Action ("AddPartialView")'}, buttons: [{icon: "glyphicon glyphicon-plus", label: "add", action: function (dialogItself) {$.post ($("form"). Attr ("action"), $("form"). SerializeArray (), function (data) {if (data.Code = 1) {BootstrapDialog.show ({message: data.Message) Buttons: [{icon: "glyphicon glyphicon-ok", label: "OK", action: function (dialogItself) {$table.bootstrapTable ("refresh") DialogItself.close (); addDialog.close ();}}]});} else BootstrapDialog.alert (data.Message);}, "json"); $("form"). Validate ();}}, {icon: "glyphicon glyphicon-remove", label: "close", action: function (dialogItself) {dialogItself.close ();}}]}); addDialog.open ();}); / / add button end

3. Delete the administrator

Considering the batch deletion, the last time I wrote AdministratorManager, I didn't write the batch deletion method, so this time I added it.

Open Ninesky.Core/AdministratorManager.cs and add the following code

/ / delete [batch] return value Code:1- successful, 2-partially deleted, 0-failed / public Response Delete (List administratorIDList) {Response _ resp = new Response (); int _ totalDel = administratorIDList.Count; int _ totalAdmin = Count (); foreach (int i in administratorIDList) {if (_ totalAdmin > 1) {base.Repository.Delete (new Administrator () {AdministratorID = I}, false); _ totalAdmin-- } else _ resp.Message = "at least one administrator needs to be retained";} _ resp.Data = base.Repository.Save (); if (_ resp.Data = = _ totalDel) {_ resp.Code = 1; _ resp.Message = "successfully deleted" + _ resp.Data + "name administrator";} else if (_ resp.Data > 0) {_ resp.Code = 2; _ resp.Message = "successfully deleted" + _ resp.Data + "name administrator" } else {_ resp.Code = 0; _ resp.Message = "deletion failed";} return _ resp;}

In addition, you need to modify the Ninesky.DataLibrary.Repository delete public int Delete (T entity, bool isSave) code to change the Remove mode to Attach, otherwise there will be an error.

/ delete entity / entity / / do you want to immediately save / return the number of affected objects if "isSave" is True, and directly return 0 public int Delete (T entity, bool isSave) {DbContext.Set (). Attach (entity); DbContext.Entry (entity). State = EntityState.Deleted; return isSave when it is False? DbContext.SaveChanges (): 0;}

Open AdminController to add DeleteJson (List ids) method

/ delete / Response.Code:1- succeeded, 2-partially deleted, 0-failed / Response.Data: number of deletions / [HttpPost] public JsonResult DeleteJson (List ids) {int _ total = ids.Count (); Response _ res = new Core.Types.Response (); int _ currentAdminID = int.Parse (Session ["AdminID"]. ToString ()); if (ids.Contains (_ currentAdminID)) {ids.Remove (_ currentAdminID) } _ res = adminManager.Delete (ids); if (_ res.Code==1&& _ res.Data)

< _total) { _res.Code = 2; _res.Message = "共提交删除"+_total+"名管理员,实际删除"+_res.Data+"名管理员。\n原因:不能删除当前登录的账号"; } else if(_res.Code ==2) { _res.Message = "共提交删除" + _total + "名管理员,实际删除" + _res.Data + "名管理员。"; } return Json(_res); } 在Index视图 script脚本区域,"//添加按钮结束"后面添加删除js代码 //添加按钮结束 //删除按钮 $("#btn_del").click(function () { var selected = $table.bootstrapTable('getSelections'); if ($(selected).length >

0) {BootstrapDialog.confirm ("OK delete selected" + $(selected). Length + "bit administrator", function (result) {if (result) {var ids = new Array ($(selected) .length); $.each (selected, function (index, value) {ids [index] = value.AdministratorID;}) Post ("@ Url.Action (" DeleteJson "," Admin ")", {ids: ids}, function (data) {if (data.Code! = 0) {BootstrapDialog.show ({message: data.Message, buttons: [{icon: "glyphicon glyphicon-ok", label: "OK", action: function (dialogItself) {$table.bootstrapTable ("refresh"); dialogItself.close ();}}]});} else BootstrapDialog.alert (data.Message) }, "json");}});} else BootstrapDialog.warning ("Please select a row to delete");}); / / end of the delete button

4. Reset password

Add the ResetPassword (int id) method to the AdminController. Reset the password to Ninesky in the.

/ reset password [Ninesky] / administrator ID / [HttpPost] public JsonResult ResetPassword (int id) {string _ password = "Ninesky"; Response _ resp = adminManager.ChangePassword (id, Security.SHA256 (_ password)); if (_ resp.Code = 1) _ resp.Message = "password reset:" + _ password; return Json (_ resp);}

In the table code snippet in adding the script code, you can see that the ResetPassword method is called through the connected onclick, so the ResetPassword method should be placed before the table generation, otherwise there will be an error that the method is not defined.

Here put the code in front of $(document) .ready.

/ / reset password function ResetPassword (id, accounts) {BootstrapDialog.confirm ("confirm reset" + accounts + "password", function (result) {if (result) {$.post ("@ Url.Action (" ResetPassword "," Admin ")", {id: id}, function (data) {BootstrapDialog.alert (data.Message);}, "json");} / / reset password end $(document) .ready (function () {/ / form

5. Change the administrator password

Add the MyInfo () method to the AdminController.

/ my profile / public ActionResult MyInfo () {return View (adminManager.Find (Session ["Accounts"]. ToString ());}

Right-click to add view

@ model Ninesky.Core.Administrator@ {ViewBag.Title = "my profile" } @ section SideNav {@ Html.Partial ("SideNavPartialView")} @ Html.ActionLink ("Home", "Index", "Home") @ Html.ActionLink ("Administrator", "Index", "Admin") my profile @ Html.Raw (ViewBag.Message) @ using (Html.BeginForm ()) {@ Html.AntiForgeryToken () @ Html.ValidationSummary (true, ", new {@ class =" text-danger "}) @ Html.LabelFor (model = > model.Accounts) HtmlAttributes: new {@ class = "control-label col-md-2"}) @ Html.DisplayTextFor (model = > model.Accounts) @ Html.LabelFor (model = > model.Password, htmlAttributes: new {@ class = "control-label col-md-2"}) @ Html.EditorFor (model = > model.Password, new {htmlAttributes = new {@ class = "form-control"}}) @ Html.ValidationMessageFor (model = > model.Password, "" New {@ class = "text-danger"}) @ Html.LabelFor (model = > model.LoginIP, htmlAttributes: new {@ class = "control-label col-md-2"}) @ Html.DisplayTextFor (model = > model.LoginIP) @ Html.LabelFor (model = > model.LoginTime, htmlAttributes: new {@ class = "control-label col-md-2"}) @ Html.DisplayTextFor (model = > model.LoginTime) @ Html.LabelFor (model = > model.CreateTime HtmlAttributes: new {@ class = "control-label col-md-2"}) @ Html.DisplayTextFor (model = > model.CreateTime)} @ section Scripts {@ Scripts.Render ("~ / bundles/jqueryval")}

Add the processing method MyInfo (FormCollection form) method to the AdminController.

[ValidateAntiForgeryToken] [HttpPost] public ActionResult MyInfo (FormCollection form) {var _ admin = adminManager.Find (Session ["Accounts"]. ToString ()); if (_ admin.Password! = form ["Password"]) {_ admin.Password = Security.SHA256 (form ["Password"]); var _ resp = adminManager.ChangePassword (_ admin.AdministratorID, _ admin.Password); if (_ resp.Code = = 1) ViewBag.Message = "password changed successfully!" ; else ViewBag.Message = "failed to change password!" ;} return View (_ admin);} about the functions of administrators in the development of ASP.NETMVC5 website, I hope the above content can be helpful to you and learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report