ASP.NET MVC5网站开发之用户资料的修改和删除3(七)_实用技巧

这次主要实现管理后台界面用户资料的修改和删除,修改用户资料和角色是经常用到的功能,但删除用户的情况比较少,为了功能的完整性还是坐上了。主要用到两个action “Modify”和“Delete”。

一、用户资料修改(Modify)

此功能分两个部分:

public ActionResult Modify(int id) 用于显示用户信息

[httppost]

public ActionResult Modify(FormCollection form)用户就收前台传来的信息并修改

1、显示用户信息

/// <summary>
  /// 修改用户信息
  /// </summary>
  /// <param name="id">用户主键</param>
  /// <returns>分部视图</returns>
  public ActionResult Modify(int id)
  {
   //角色列表
   var _roles = new RoleManager().FindList();
   List<SelectListItem> _listItems = new List<SelectListItem>(_roles.Count());
   foreach (var _role in _roles)
   {
    _listItems.Add(new SelectListItem() { Text = _role.Name, Value = _role.RoleID.ToString() });
   }
   ViewBag.Roles = _listItems;
   //角色列表结束
   return PartialView(userManager.Find(id));
  }

此action有一个参数id,接收传入的用户ID,在action中查询角色信息,并利用viewBage传递到视图,并通过return PartialView(userManager.Find(id))向视图传递用户模型返回分部视图。

视图代码如下:

@model Ninesky.Core.User

@using (Html.BeginForm())
{
 @Html.AntiForgeryToken()

 <div class="form-horizontal">
  @Html.ValidationSummary(true, "", new { @class = "text-danger" })
  @Html.HiddenFor(model => model.UserID)

  <div class="form-group">
   @Html.LabelFor(model => model.RoleID, htmlAttributes: new { @class = "control-label col-md-2" })
   <div class="col-md-10">
    @Html.DropDownListFor(model => model.RoleID, (IEnumerable<SelectListItem>)ViewBag.Roles, new { @class = "form-control" })
    @Html.ValidationMessageFor(model => model.RoleID, "", new { @class = "text-danger" })
   </div>
  </div>

  <div class="form-group">
   @Html.LabelFor(model => model.Username, htmlAttributes: new { @class = "control-label col-md-2" })
   <div class="col-md-10">
    @Html.EditorFor(model => model.Username, new { htmlAttributes = new { @class = "form-control", disabled = "disabled" } })
    @Html.ValidationMessageFor(model => model.Username, "", new { @class = "text-danger" })
   </div>
  </div>

  <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, "", new { @class = "text-danger" })
   </div>
  </div>

  <div class="form-group">
   @Html.LabelFor(model => model.Sex, htmlAttributes: new { @class = "control-label col-md-2" })
   <div class="col-md-10">
    @Html.RadioButtonFor(model => model.Sex, 1) 男
    @Html.RadioButtonFor(model => model.Sex, 0) 女
    @Html.RadioButtonFor(model => model.Sex, 2) 保密
    @Html.ValidationMessageFor(model => model.Sex, "", new { @class = "text-danger" })
   </div>
  </div>

  <div class="form-group">
   @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })
   <div class="col-md-10">
    @Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })
    @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })
   </div>
  </div>

  <div class="form-group">
   @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
   <div class="col-md-10">
    @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
    @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
   </div>
  </div>

  <div class="form-group">
   @Html.LabelFor(model => model.LastLoginTime, htmlAttributes: new { @class = "control-label col-md-2" })
   <div class="col-md-10">
    @Html.EditorFor(model => model.LastLoginTime, new { htmlAttributes = new { @class = "form-control", disabled = "disabled" } })
    @Html.ValidationMessageFor(model => model.LastLoginTime, "", new { @class = "text-danger" })
   </div>
  </div>

  <div class="form-group">
   @Html.LabelFor(model => model.LastLoginIP, htmlAttributes: new { @class = "control-label col-md-2" })
   <div class="col-md-10">
    @Html.EditorFor(model => model.LastLoginIP, new { htmlAttributes = new { @class = "form-control", disabled = "disabled" } })
    @Html.ValidationMessageFor(model => model.LastLoginIP, "", new { @class = "text-danger" })
   </div>
  </div>

  <div class="form-group">
   @Html.LabelFor(model => model.RegTime, htmlAttributes: new { @class = "control-label col-md-2" })
   <div class="col-md-10">
    @Html.EditorFor(model => model.RegTime, new { htmlAttributes = new { @class = "form-control", disabled = "disabled" } })
    @Html.ValidationMessageFor(model => model.RegTime, "", new { @class = "text-danger" })
   </div>
  </div>

 </div>
}

2、修改用户资料的后台处理

[HttpPost]
  [ValidateAntiForgeryToken]
  public ActionResult Modify(int id,FormCollection form)
  {
   Response _resp = new Auxiliary.Response();
   var _user = userManager.Find(id);
   if (TryUpdateModel(_user, new string[] { "RoleID", "Name", "Sex", "Email" }))
   {
    if (_user == null)
    {
     _resp.Code = 0;
     _resp.Message = "用户不存在,可能已被删除,请刷新后重试";
    }
    else
    {
     if (_user.Password != form["Password"].ToString()) _user.Password = Security.SHA256(form["Password"].ToString());
     _resp = userManager.Update(_user);
    }
   }
   else
   {
    _resp.Code = 0;
    _resp.Message = General.GetModelErrorString(ModelState);
   }
   return Json(_resp);
  }

此方法有两个参数id 和FormCollection form,不用User直接做模型的原因是因为user会把前台所有数据都接收过来,这里我并不想允许修改用户名,所以在方法中使用TryUpdateModel绑定允许用户修改的属性。TryUpdateModel在绑定失败时同样会在在ModelState中记录错误,可以利用自定义方法GetModelErrorString获取到错误信息并反馈给视图。

2、前台显示和处理

打开Index视图找到表格初始化方法,格式化列“Username”使其显示一个连接,代码红线部分。

使其看起来这个样子,当用户点击连接的时候可以显示修改对话框

弹出窗口和发送到服务器的js代码写到表格的onLoadSuccess方法里

onLoadSuccess: function () {

     //修改
     $("a[data-method='Modify']").click(function () {
      var id = $(this).attr("data-value");
      var modifyDialog = new BootstrapDialog({
       title: "<span class='glyphicon glyphicon-user'></span>修改用户",
       message: function (dialog) {
        var $message = $('<div></div>');
        var pageToLoad = dialog.getData('pageToLoad');
        $message.load(pageToLoad);

        return $message;
       },
       data: {
        'pageToLoad': '@Url.Action("Modify")/' + id
       },
       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();
              modifyDialog.close();
             }
            }]

           });
          }
          else BootstrapDialog.alert(data.Message);
         }, "json");
         $("form").validate();
        }
       }, {
        icon: "glyphicon glyphicon-remove",
        label: "关闭",
        action: function (dialogItself) {
         dialogItself.close();
        }
       }]
      });
      modifyDialog.open();
     });
     //修改结束
}

显示效果如下图

二、删除用户

UserController中添加删除方法

/// <summary>
  /// 删除
  /// </summary>
  /// <param name="id">用户ID</param>
  /// <returns></returns>
  [HttpPost]
  public ActionResult Delete(int id)
  {
   return Json(userManager.Delete(id));
  }

打开Index视图找到表格初始化方法,添加“操作”列格式化列使其显示一个删除按钮,代码红框部分。

前台显示效果

然后在表格的onLoadSuccess方法里刚写的修改用户信息的js代码后面写删除用户的js代码

//修改结束

     //删除按钮
     $("a[data-method='Delete']").click(function () {
      var id = $(this).attr("data-value");
      BootstrapDialog.confirm("你确定要删除" + $(this).parent().parent().find("td").eq(3).text() + "吗?\n 建议尽可能不要删除用户。", function (result) {
       if (result) {
        $.post("@Url.Action("Delete", "User")", { id: id }, function (data) {
         if (data.Code == 1) {
          BootstrapDialog.show({
           message: "删除用户成功",
           buttons: [{
            icon: "glyphicon glyphicon-ok",
            label: "确定",
            action: function (dialogItself) {
             $table.bootstrapTable("refresh");
             dialogItself.close();
            }
           }]

          });
         }
         else BootstrapDialog.alert(data.Message);
        }, "json");
       }
      });
     });
     //删除按钮结束
    }
   });
   //表格结束

前台显示效果

==========================================

代码下载请见http://www.cnblogs.com/mzwhj/p/5729848.html

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

以上是小编为您精心准备的的内容,在的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索asp.net
, 网站
, mvc5
, 用户资料修改
用户资料删除
,以便于您获取更多的相关知识。

时间: 2024-09-10 05:11:00

ASP.NET MVC5网站开发之用户资料的修改和删除3(七)_实用技巧的相关文章

ASP.NET MVC5网站开发之实现数据存储层功能(三)_实用技巧

数据存储层在项目Ninesky.DataLibrary中实现,整个项目只有一个类Repository. Repository中实现增删改查询等方法供业务逻辑层调用,主要功能如下图: 具体步骤 一.添加实体框架的引用 1.打开解决方案,选择项目Ninesky.DataLibrary,在引用上右键,选择管理NuGet程序包. 在NuGet包管理器中的浏览标签中点击EntityFramework,点击右侧栏的安装按钮. 在搜索框输入EntityFramework.zh-Hans,安装假体中文资源包.

ASP.NET MVC5网站开发之用户添加和浏览2(七)_实用技巧

一.数据存储层 1.查找分页列表 在写用户列表时遇到了问题,考虑到用户可能会较多的情况需要分页,在数据存储层写的方法是public IQueryable<T> FindPageList<TKey>(int pageSize, int pageIndex, out int totalNumber, Expression<Func<T, bool>> where, Expression<Func<T, TKey>> order, bool

ASP.NET MVC5实现文件上传与地址变化处理(5)_实用技巧

一.上传文件和重复文件处理文件处理的原则是:不在数据库中保存文件,只在数据库中保存文件信息(Hash值等).采取文件的MD5重命名文件在一般情况足够处理文件的重复问题,强迫症倾向则可以考虑将MD5和其他摘要算法结合. public static string Save(HttpPostedFileBase file, string path) { var root = "~/Upload/" + path + "/"; var phicyPath = Hosting

asp.net中ListBox 绑定多个选项为选中及删除实现方法_实用技巧

我们先来看listbox绑定多选项实现 复制代码 代码如下: <%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"

ASP.NET MVC5网站开发概述(一)_实用技巧

前段时间一直在用MVC4写个网站开发的demo,由于刚开始学所有的代码都写在一个项目中,越写越混乱,到后来有些代码自己都理不清了.正好看到别人在用MVC5写东西,喜新厌旧的我马上下载了Visual Studio 2013,幸好MVC4到MVC5变化不大,这次准备用MVC5重新写个Demo. 每次看以前写的代码总有把它丢进回收站的冲动,其实没有完美的代码,能解决问题的代码就算是好代码吧,但是我还是决定重新写一个学习的Demo,希望这次能有提高,希望这次能写完吧! 一.开发环境 1.开发环境: Vi

ASP.NET MVC5网站开发用户注册(四)_实用技巧

一.默认Web项目的更改 用户这部分还是自己做,所以删除自动生成的用户相关代码. 二.添加Member区域 在web项目上点右键 添加 区域Member. 添加Home控制器,选择MVC5控制器-空 我们给public ActionResult Index()添加一个视图,代码很简单就是显示下用户名 @{ ViewBag.Title = "会员中心"; } <h2>欢迎你!@User.Identity.Name </h2> 我们先运行一下,出错啦. 这是因为项目

ASP.NET MVC5网站开发我的咨询列表及添加咨询(十二)_实用技巧

上次把咨询的架构搭好了,现在分两次来完成咨询:1.用户部分,2管理部分.这次实现用户部分,包含两个功能,查看我的咨询和进行咨询. 一.菜单 打开上次添加的ConsultationController控制器,添加Menu action,返回分布视图 /// <summary> /// 菜单 /// </summary> /// <returns></returns> public ActionResult Menu() { return PartialView

ASP.NET MVC5网站开发修改及删除文章(十)_实用技巧

上次做了显示文章列表,再实现修改和删除文章这部分内容就结束了,这次内容比较简单,由于做过了添加文章,修改文章非常类似,就是多了一个TryUpdateModel部分更新模型数据.一.删除文章 由于公共模型跟,文章,附件有关联,所以这里的删除次序很重要,如果先删除模型,那么文章ModelID和附件的ModelID多会变成null,所以要先先删除文章和附件再删除公共模型. 由于公共模型和附件是一对多的关系,我们把删除公共模型和删除附件写在一起. 在BLL的BaseRepository类中有默认的Del

ASP.NET MVC5网站开发咨询管理的架构(十一)_实用技巧

一.总体说明 1.实现功能 2.类图 由于文章部分把大部分类都是实现了,这里仅多了一个Consultation类. 二.创建咨询模型类 在Ninesky.Models项目添加类Consultation(咨询模型),该模型跟Article类似都是CommonModel的扩展.1.添加Consultation类. using System; using System.ComponentModel.DataAnnotations; namespace Ninesky.Models { /// <sum