ASP.NETMVC5网站开发中关于管理员的功能有哪些
创始人
2024-11-28 09:23:12
0次

一、安装插件。 

展示层前端框架以Bootstrap为主,因为Bootstrap的js功能较弱,这里添加一些插件作补充。其实很多js插件可以通过NuGet安装,只是NuGet安装时添加的内容较多,不如自己复制来的干净,所以这里所有的插件都是下载然后复制到项目中。 

1、Bootstrap 3 Datepicker 4.17.37
网址:https://eonasdan.github.io/bootstrap-datetimepicker/ 

下载并解压压缩包->将bootstrap-datetimepicker.js和bootstrap-datetimepicker.min.js复制到Ninesy.Web项目的Scripts文件夹,将bootstrap-datetimepicker.css和bootstrap-datetimepicker.min.css复制到Content文件夹。 

2、bootstrap-dialog 3.3.4.1 
网址:https://github.com/nakupanda/bootstrap3-dialog 

下载并解压压缩包->将.js复制到Ninesy.Web项目的Scripts文件夹,将.css复制到Content文件夹。 

3、bootstrap-select  1.10.0
网址:http://silviomoreto.github.io/bootstrap-select/ 

下载并解压压缩包->将bootstrap-select.js复制到Ninesy.Web项目的Scripts文件夹,和defaults-zh_CN.js重命名为bootstrap-select-zh_CN.js复制到Ninesy.Web项目的Scripts文件夹,将bootstrap-select.css、bootstrap-select.css.map和bootstrap-select.min.css复制到Content文件夹。 

4、bootstrap-table 1.10.1

网址:http://bootstrap-table.wenzhixin.net.cn/
下载并解压压缩包->将bootstrap-table.js和bootstrap-table-zh-CN.js复制到Ninesy.Web项目的Scripts文件夹,将bootstrap-table.css复制到Content文件夹。 

5、Bootstrap TreeView 1.2.0 

网址:https://github.com/jonmiles/bootstrap-treeview 

下载并解压压缩包->将bootstrap-treeview.js复制到Ninesy.Web项目的Scripts文件夹,将bootstrap-treeview.css复制到Content文件夹。

6、twbs-pagination
网址:http://esimakin.github.io/twbs-pagination/

下载并解压压缩包->将jquery.twbsPagination.js和jquery.twbsPagination.min.js复制到Ninesy.Web项目的Scripts文件夹。 

7、对js和css进行捆绑和压缩
打开Ninesky.Web->App_Start->BundleConfig.cs。添加红框内的代码。

ASP.NETMVC5网站开发中关于管理员的功能有哪些

二、获取ModelState错误信息的方法
在项目中有些内容是通过AJAX方法提交,如果提交时客户端没有进行验证,在服务器端进行验证时会将错误信息保存在ModelState中,这里需要写一个方法来获取ModelState的错误信息,以便反馈给客户端。 

1、Ninesk.Web【右键】->添加->类,输入类名General。
 引用命名空间using System.Web.Mvc和System.Text。
 添加静态方法GetModelErrorString(),该方法用来获取模型的错误字符串。 

using System.Linq;
using System.Text;
using System.Web.Mvc;

namespace Ninesky.Web
{
 /// 
 /// 通用类
 /// 
 public class General
 {
 /// 
 /// 获取模型错误
 /// 
 /// 模型状态
 /// 
 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();
 }
 }
}

三、完善布局页
 上次完成了管理员登录,这次要进行登录后的一些功能,要先把后台的布局页充实起来。 
打开 Ninesky.Web/Areas/Control/Views/_Layout.cshtml。整成下面的代码。自己渣一样的美工,具体过程就不写了。 




 
 
 @ViewBag.Title - 系统管理
 @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 系统管理", "Index", "Home", new { area = "Control" }, new { @class = "navbar-brand" })
 
     
  •  用户管理
  •  
  •  管理员
  •  
  •  栏目设置
  •  
  •  网站设置
  •      
  •   @Context.Session["Accounts"].ToString()  
  •  
  •   退出  
  •    
     
     
         @RenderSection("SideNav", false)
     @RenderBody()
     
         

    © Ninesky v0.1 BASE BY 洞庭夕照 http://mzwhj.cnblogs.com

       

    ASP.NETMVC5网站开发中关于管理员的功能有哪些

    反正效果就是这个样子了。 

    三、功能实现
    按照设想,要在Index界面完成管理员的浏览、添加和删除功能。这些功能采用ajax方式。
    在添加AdminController的时候自动添加了Index()方法。

    添加Index视图 

    在Index方法上右键添加视图 

    ASP.NETMVC5网站开发中关于管理员的功能有哪些

    @{
     ViewBag.Title = "管理员";
    }
    
    
     
  •  @Html.ActionLink("首页", "Index", "Home")
  •  @Html.ActionLink("管理员", "Index", "Admin") @section style{  @Styles.Render("~/Content/bootstrapplugincss") } @section scripts{  @Scripts.Render("~/bundles/jqueryval")  @Scripts.Render("~/bundles/bootstrapplugin")   }

    添加侧栏导航视图
    Ninesky.Web/Areas/Control/Views/Admin【右键】->添加->视图 

    ASP.NETMVC5网站开发中关于管理员的功能有哪些

    视图代码如下 

    
     
      管理员
     
          @Html.ActionLink("管理","Index")
       

    在Index视图中添加@section SideNav{@Html.Partial("SideNavPartialView")}(如图)

    ASP.NETMVC5网站开发中关于管理员的功能有哪些

    1、管理员列表
     在Admin控制器中添加ListJson()方法 

    /// 
     /// 管理员列表
     /// 
     /// 
     public JsonResult ListJson()
     {
     return Json(adminManager.FindList());
     }

    为在index中使用bootstrap-table显示和操作管理员列表,在index视图中添加下图代码。 

    
      添加
      删除
    
    

    在@section scripts{ } 中添加js代码 

    
    
     $(document).ready(function () {
    
     //表格
     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: "帐号", field: "Accounts" },
     { title: "登录时间", field: "LoginTime", formatter: function (value) { return moment(value).format("YYYY-MM-DD HH:mm:ss") } },
     { title: "登录IP", field: "LoginIP" },
     { title: "创建时间", field: "CreateTime", formatter: function (value) { return moment(value).format("YYYY-MM-DD HH:mm:ss") } },
     { title: "操作", field: "AdministratorID", formatter: function (value, row, index) { return "重置密码" } }
     ]
     });
     //表格结束
     });
     
    }

    显示效果如图: 

    ASP.NETMVC5网站开发中关于管理员的功能有哪些

    2、添加管理员
     在控制器中添加AddPartialView()方法 

    /// 
     /// 添加【分部视图】
     /// 
     /// 
     public PartialViewResult AddPartialView()
     {
     return PartialView();
     }

    Models文件夹【右键】->添加->类,输入类名 AddAdminViewModel。 

    using System.ComponentModel.DataAnnotations;
    
    namespace Ninesky.Web.Areas.Control.Models
    {
     /// 
     /// 添加管理员模型
     /// 
     public class AddAdminViewModel
     {
     /// 
     /// 帐号
     /// 
     [Required(ErrorMessage = "必须输入{0}")]
     [StringLength(30, MinimumLength = 4, ErrorMessage = "{0}长度为{2}-{1}个字符")]
     [Display(Name = "帐号")]
     public string Accounts { get; set; }
    
     /// 
     /// 密码
     /// 
     [DataType(DataType.Password)] [Required(ErrorMessage = "必须输入{0}")]
     [StringLength(20,MinimumLength =6, ErrorMessage = "{0}长度少于{1}个字符")]
     [Display(Name = "密码")]
     public string Password { get; set; }
     }
    }

    右键添加视图

    ASP.NETMVC5网站开发中关于管理员的功能有哪些

    注意:抓图的时候忘记勾上引用脚本库了就抓了,记得勾上。

    @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")

    在Index视图 script脚本区域,“//表格结束”后面添加js代码 

    //表格结束
     //工具栏
     //添加按钮
     $("#btn_add").click(function () {
     var addDialog = new BootstrapDialog({
     title: "添加管理员",
     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: "添加",  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: "确定",   action: function (dialogItself) {   $table.bootstrapTable("refresh");   dialogItself.close();   addDialog.close();   }   }]   });  }  else BootstrapDialog.alert(data.Message);  }, "json");  $("form").validate();  }  }, {  icon: "glyphicon glyphicon-remove",  label: "关闭",  action: function (dialogItself) {  dialogItself.close();  }  }]  });  addDialog.open();  });  //添加按钮结束

    ASP.NETMVC5网站开发中关于管理员的功能有哪些

    3、删除管理员 
    考虑到批量删除,上次写AdministratorManager没有写批量删除方法,这次补上。 
    打开Ninesky.Core/AdministratorManager.cs, 添加如下代码 

    /// 
     /// 删除【批量】返回值Code:1-成功,2-部分删除,0-失败
     /// 
     /// 
     /// 
     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 = "最少需保留1名管理员";
     }
     _resp.Data = base.Repository.Save();
     if(_resp.Data == _totalDel)
     {
     _resp.Code = 1;
     _resp.Message = "成功删除" + _resp.Data + "名管理员";
     }
     else if (_resp.Data > 0)
     {
     _resp.Code = 2;
     _resp.Message = "成功删除" + _resp.Data + "名管理员";
     }
     else
     {
     _resp.Code = 0;
     _resp.Message = "删除失败";
     }
     return _resp;
     }

    另外要修改一下Ninesky.DataLibrary.Repository的删除public int Delete(T entity, bool isSave)代码将Remove方式 改为Attach,不然会出错。 

    /// 
     /// 删除实体
     /// 
     /// 实体
     /// 是否立即保存
     /// 在“isSave”为True时返回受影响的对象的数目,为False时直接返回0
     public int Delete(T entity, bool isSave)
     {
     DbContext.Set().Attach(entity);
     DbContext.Entry(entity).State = EntityState.Deleted;
     return isSave ? DbContext.SaveChanges() : 0;
     }

    打开AdminController 添加DeleteJson(List ids)方法 

    // 
     /// 删除 
     /// Response.Code:1-成功,2-部分删除,0-失败
     /// Response.Data:删除的数量
     /// 
     /// 
     [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("确定删除选中的" + $(selected).length + "位管理员", 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: "确定",
      action: function (dialogItself) {
      $table.bootstrapTable("refresh");
      dialogItself.close();
      }
      }]
    
      });
     }
     else BootstrapDialog.alert(data.Message);
    
     }, "json");
     }
     });
     }
     else BootstrapDialog.warning("请选择要删除的行");
     });
     //删除按钮结束

    4、重置密码
     在AdminController中 添加ResetPassword(int id)方法。方法中将密码重置为Ninesky。 

    /// 
     /// 重置密码【Ninesky】
     /// 
     /// 管理员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;
     return Json(_resp);
     }

    在添加script代码中表格代码段可以看到,这里通过 连接的onclick调用ResetPassword方法,所以ResetPassword方法要放在表格生成前面,不然会出现 方法未定义的错误。 

    ASP.NETMVC5网站开发中关于管理员的功能有哪些

    这里把代码放到$(document).ready的前面。 

     //重置密码
     function ResetPassword(id, accounts) {
     BootstrapDialog.confirm("确定重置" + accounts + "的密码", function (result) {
     if (result) {
     $.post("@Url.Action("ResetPassword", "Admin")", { id: id }, function (data) {
     BootstrapDialog.alert(data.Message);
     }, "json");
     }
     });
     };
     //重置密码结束
    
     $(document).ready(function () {
    
     //表格

    5、修改管理员密码 
    在在AdminController中 添加MyInfo()方法。 

    /// 
     /// 我的资料
     /// 
     /// 
     public ActionResult MyInfo()
     {
     return View(adminManager.Find(Session["Accounts"].ToString()));
     }

    右键添加视图 

    ASP.NETMVC5网站开发中关于管理员的功能有哪些

    @model Ninesky.Core.Administrator
    
    @{
     ViewBag.Title = "我的资料";
    }
    
    @section SideNav{@Html.Partial("SideNavPartialView")}
    
    
     
  •  @Html.ActionLink("首页", "Index", "Home")
  •  
  • @Html.ActionLink("管理员", "Index", "Admin")
  •  我的资料 @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") }

    在在AdminController中 添加处理方法MyInfo(FormCollection form)方法。 

    [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 = "修改密码成功!";
     else ViewBag.Message = "修改密码失败!";
     }
     return View(_admin);
     }

    上一篇:ASP.NETMVC5网站开发中如何实现用户角色的后台管理

    下一篇:ASP.NETMVC5网站开发中如何实现登录验证和注销管理员

    相关内容

    热门资讯

    空调连续工作多久需要停机休息 空调连续工作的时间取决于多个因素,包括空调的型号、功率、使用环境和维护情况等。一般来说,空调可以连续...
    空调哪个符号是除湿的 空调除湿功能通常用一个水滴形状的符号表示。不同品牌和型号的空调遥控器可能会有所差异,但一般来说,除湿...
    格力空调多长时间加一次氟利昂 1、一般情况下,空调对氟利昂的使用量是非常小的,所以在空调使用了四年左右的时候再考虑加也没问题。2、...
    空调用多长时间需要加氟一次 一般情况下是五年。当出现以下这几种情况时,空调才需要加氟。1、空调的室内机和室外机各有两个接口,当接...
    格调生活·C标思享荟:卡萨帝在... 9月12日的郑州龙湖金融岛,夜风轻拂,灯光璀璨。“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑...
    品牌价值破千亿、高端份额持续领... 9月12日,“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑州站”在郑州龙湖金融岛举办。2026...
    空调主板坏了修800还是换新的 空调主板坏了是修还是换新,需要考虑多个因素,以下是一些建议:1. 维修成本:如果维修费用较低,比如 ...
    空调开多久需要休息多长时间 问题:空调开多久需要休息多长时间回答:1、在使用空调的过程中,一般空调开7~8个小时左右需要休息2~...
    中央空调多长时间清洗一次 1、一般空调开机前清洗一次即可,空调开机中间时段再清洗一次,空调关机时清洗一次,这样比较合理。2、空...
    中央空调氟利昂多久加一次 看空调制热和制冷程度,很多人的观点认为氟利昂必须一年放一次,其实这个观点是错误的,理解上面有点偏差,...