欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-12-04 22:36:46
这次主要实现管理后台界面用户资料的修改和删除,修改用户资料和角色是经常用到的功能,但删除用户的情况比较少,为了功能的完整性还是坐上了。主要用到两个action “modif...

这次主要实现管理后台界面用户资料的修改和删除,修改用户资料和角色是经常用到的功能,但删除用户的情况比较少,为了功能的完整性还是坐上了。主要用到两个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”使其显示一个连接,代码红线部分。

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

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

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

弹出窗口和发送到服务器的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();
     });
     //修改结束
}

显示效果如下图

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

二、删除用户

usercontroller中添加删除方法

/// <summary>
  /// 删除
  /// </summary>
  /// <param name="id">用户id</param>
  /// <returns></returns>
  [httppost]
  public actionresult delete(int id)
  {
   return json(usermanager.delete(id));
  }

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

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

前台显示效果

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

然后在表格的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");
       }
      });
     });
     //删除按钮结束
    }
   });
   //表格结束

前台显示效果

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

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

代码下载请见

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