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

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

程序员文章站 2023-12-04 22:17:10
一、数据存储层 1、查找分页列表 在写用户列表时遇到了问题,考虑到用户可能会较多的情况需要分页,在数据存储层写的方法是public iqueryable

一、数据存储层

1、查找分页列表

在写用户列表时遇到了问题,考虑到用户可能会较多的情况需要分页,在数据存储层写的方法是public iqueryable<t> findpagelist<tkey>(int pagesize, int pageindex, out int totalnumber, expression<func<t, bool>> where, expression<func<t, tkey>> order, bool asc)。

主要问题就在红色的order这儿,这个参数不好传递,比如:如果是已id来排序哪tkey类型是int,如果以注册时间来排序哪tkey类型就是datetime。如果我在业务逻辑层写一个函数可以支持选择排序类型,那么我没有办法声明一个变量既可以存储tkey为int的值,又可以存储datetime的值,那么排序就要写成下面这个样子,感觉不舒服。

//排序
      switch(order)
      {
        case 0://id升序
          _users.items = repository.findpagelist((int)pagesize, (int)pageindex, out _users.totalnumber, _where, u => u.userid, true).tolist();
          break;
        case 1://id降序
          _users.items = repository.findpagelist((int)pagesize, (int)pageindex, out _users.totalnumber, _where, u => u.userid, false).tolist();
          break;
        case 2://注册时间降序
          _users.items = repository.findpagelist((int)pagesize, (int)pageindex, out _users.totalnumber, _where, u => u.regtime, true).tolist();
          break;
        case 3://注册时间升序
          _users.items = repository.findpagelist((int)pagesize, (int)pageindex, out _users.totalnumber, _where, u => u.regtime, false).tolist();
          break;
        case 4://最后登录时间升序
          _users.items = repository.findpagelist((int)pagesize, (int)pageindex, out _users.totalnumber, _where, u => u.lastlogintime, true).tolist();
          break;
        case 5://最后登录时间降序
          _users.items = repository.findpagelist((int)pagesize, (int)pageindex, out _users.totalnumber, _where, u => u.lastlogintime, false).tolist();
          break;
        default://id降序
          _users.items = repository.findpagelist((int)pagesize, (int)pageindex, out _users.totalnumber, _where, u => u.userid, false).tolist();
          break;
      }

后来将tkey设为dynamic类型,不论expression<func<t, dynamic>> order = u => u.userid  或者u => u.regtime都可以编译通过,但是一运行就会出错。

前几天没写博客一直在考虑这个问题,后来还是换成用字符串的方式来动态排序。 步骤如下:

ninesky.datalibrary[右键]->添加->类,输入类名orderparam

namespace ninesky.datalibrary
{
  /// <summary>
  /// 排序参数
  /// </summary>
  public class orderparam
  {
    /// <summary>
    /// 属性名
    /// </summary>
    public string propertyname { get; set; }

    /// <summary>
    /// 排序方式
    /// </summary>
    public ordermethod method { get; set; }
  }

  /// <summary>
  /// 排序方式
  /// </summary>
  public enum ordermethod
  {
    /// <summary>
    /// 正序
    /// </summary>
    asc,
    /// <summary>
    /// 倒序
    /// </summary>
    desc
  }
}

打开ninesky.datalibrary/repository.cs,将方法public iqueryable<t> findpagelist<tkey>(int pagesize, int pageindex, out int totalnumber, expression<func<t, bool>> where, expression<func<t, tkey>> order, bool asc)的代码修改为

/// <summary>
    /// 查找分页列表
    /// </summary>
    /// <param name="pagesize">每页记录数。必须大于1</param>
    /// <param name="pageindex">页码。首页从1开始,页码必须大于1</param>
    /// <param name="totalnumber">总记录数</param>
    /// <param name="where">查询表达式</param>
    /// <param name="orderparams">排序【null-不设置】</param>
    public iqueryable<t> findpagelist(int pagesize, int pageindex, out int totalnumber, expression<func<t, bool>> where, orderparam[] orderparams)
    {
      if (pageindex < 1) pageindex = 1;
      if (pagesize < 1) pagesize = 10;
      iqueryable<t> _list = dbcontext.set<t>().where(where);
      var _orderparames = expression.parameter(typeof(t), "o");
      if (orderparams != null && orderparams.length > 0)
      {
        for (int i = 0; i < orderparams.length; i++)
        {
          //根据属性名获取属性
          var _property = typeof(t).getproperty(orderparams[i].propertyname);
          //创建一个访问属性的表达式
          var _propertyaccess = expression.makememberaccess(_orderparames, _property);
          var _orderbyexp = expression.lambda(_propertyaccess, _orderparames);
          string _ordername = orderparams[i].method == ordermethod.asc ? "orderby" : "orderbydescending";
          methodcallexpression resultexp = expression.call(typeof(queryable), _ordername, new type[] { typeof(t), _property.propertytype }, _list.expression, expression.quote(_orderbyexp));
          _list = _list.provider.createquery<t>(resultexp);
        }
      }
      totalnumber = _list.count();
      return _list.skip((pageindex - 1) * pageindex).take(pagesize);
    }

方法中排序参数(orderparam[]) 使用数组,是考虑到多级排序的情况。对findpagelist重载代码进行修改,修改完的代码如下:

//查找实体分页列表
    #region findpagelist

    /// <summary>
    /// 查找分页列表
    /// </summary>
    /// <param name="pagesize">每页记录数。必须大于1</param>
    /// <param name="pageindex">页码。首页从1开始,页码必须大于1</param>
    /// <param name="totalnumber">总记录数</param>
    /// <returns></returns>
    public iqueryable<t> findpagelist(int pagesize, int pageindex, out int totalnumber)
    {
      orderparam _orderparam = null;
      return findpagelist(pagesize, pageindex, out totalnumber, _orderparam);
    }

    /// <summary>
    /// 查找分页列表
    /// </summary>
    /// <param name="pagesize">每页记录数。必须大于1</param>
    /// <param name="pageindex">页码。首页从1开始,页码必须大于1</param>
    /// <param name="totalnumber">总记录数</param>
    /// <param name="order">排序键</param>
    /// <param name="asc">是否正序</param>
    /// <returns></returns>
    public iqueryable<t> findpagelist(int pagesize, int pageindex, out int totalnumber, orderparam orderparam)
    {
      return findpagelist(pagesize, pageindex, out totalnumber, (t)=> true, orderparam);
    }

    /// <summary>
    /// 查找分页列表
    /// </summary>
    /// <param name="pagesize">每页记录数。必须大于1</param>
    /// <param name="pageindex">页码。首页从1开始,页码必须大于1</param>
    /// <param name="totalnumber">总记录数</param>
    /// <param name="where">查询表达式</param>
    public iqueryable<t> findpagelist(int pagesize, int pageindex, out int totalnumber, expression<func<t, bool>> where)
    {
      orderparam _param = null;
      return findpagelist(pagesize, pageindex, out totalnumber, where, _param);
    }

    /// <summary>
    /// 查找分页列表
    /// </summary>
    /// <param name="pagesize">每页记录数。</param>
    /// <param name="pageindex">页码。首页从1开始</param>
    /// <param name="totalnumber">总记录数</param>
    /// <param name="where">查询表达式</param>
    /// <param name="orderparam">排序【null-不设置】</param>
    /// <returns></returns>
    public iqueryable<t> findpagelist(int pagesize, int pageindex, out int totalnumber, expression<func<t, bool>> where, orderparam orderparam)
    {
      orderparam[] _orderparams = null;
      if (orderparam != null) _orderparams = new orderparam[] { orderparam };
      return findpagelist(pagesize, pageindex, out totalnumber, where, _orderparams);
    }

    /// <summary>
    /// 查找分页列表
    /// </summary>
    /// <param name="pagesize">每页记录数。</param>
    /// <param name="pageindex">页码。首页从1开始</param>
    /// <param name="totalnumber">总记录数</param>
    /// <param name="where">查询表达式</param>
    /// <param name="orderparams">排序【null-不设置】</param>
    public iqueryable<t> findpagelist(int pagesize, int pageindex, out int totalnumber, expression<func<t, bool>> where, orderparam[] orderparams)
    {
      if (pageindex < 1) pageindex = 1;
      if (pagesize < 1) pagesize = 10;
      iqueryable<t> _list = dbcontext.set<t>().where(where);
      var _orderparames = expression.parameter(typeof(t), "o");
      if (orderparams != null && orderparams.length > 0)
      {
        for (int i = 0; i < orderparams.length; i++)
        {
          //根据属性名获取属性
          var _property = typeof(t).getproperty(orderparams[i].propertyname);
          //创建一个访问属性的表达式
          var _propertyaccess = expression.makememberaccess(_orderparames, _property);
          var _orderbyexp = expression.lambda(_propertyaccess, _orderparames);
          string _ordername = orderparams[i].method == ordermethod.asc ? "orderby" : "orderbydescending";
          methodcallexpression resultexp = expression.call(typeof(queryable), _ordername, new type[] { typeof(t), _property.propertytype }, _list.expression, expression.quote(_orderbyexp));
          _list = _list.provider.createquery<t>(resultexp);
        }
      }
      totalnumber = _list.count();
      return _list.skip((pageindex - 1) * pageindex).take(pagesize);
    }

    #endregion

2、查找列表

基于分页列表同样的原因,对findlist方法也进行修改。

//查找实体列表
    #region findlist
    /// <summary>
    /// 查找实体列表
    /// </summary>
    /// <returns></returns>
    public iqueryable<t> findlist()
    {
      return dbcontext.set<t>();
    }

    /// <summary>
    /// 查找实体列表
    /// </summary>
    /// <param name="where">查询lambda表达式</param>
    /// <returns></returns>
    public iqueryable<t> findlist(expression<func<t, bool>> where)
    {
      return dbcontext.set<t>().where(where);
    }

    /// <summary>
    /// 查找实体列表
    /// </summary>
    /// <param name="where">查询lambda表达式</param>
    /// <param name="number">获取的记录数量</param>
    /// <returns></returns>
    public iqueryable<t> findlist(expression<func<t, bool>> where, int number)
    {
      return dbcontext.set<t>().where(where).take(number);
    }

    /// <summary>
    /// 查找实体列表
    /// </summary>
    /// <param name="where">查询lambda表达式</param>
    /// <param name="orderparam">排序参数</param>
    /// <returns></returns>
    public iqueryable<t> findlist(expression<func<t, bool>> where, orderparam orderparam)
    {
      return findlist(where, orderparam, 0);
    }

    /// <summary>
    /// 查找实体列表
    /// </summary>
    /// <param name="where">查询lambda表达式</param>
    /// <param name="orderparam">排序参数</param>
    /// <param name="number">获取的记录数量【0-不启用】</param>
    public iqueryable<t> findlist(expression<func<t, bool>> where, orderparam orderparam, int number)
    {
      orderparam[] _orderparams = null;
      if (orderparam != null) _orderparams = new orderparam[] { orderparam };
      return findlist(where, _orderparams, number);
    }

    /// <summary>
    /// 查找实体列表
    /// </summary>
    /// <param name="where">查询lambda表达式</param>
    /// <param name="orderparams">排序参数</param>
    /// <param name="number">获取的记录数量【0-不启用】</param>
    /// <returns></returns>
    public iqueryable<t> findlist(expression<func<t, bool>> where, orderparam[] orderparams, int number)
    {
      var _list = dbcontext.set<t>().where(where);
      var _orderparames = expression.parameter(typeof(t), "o");
      if (orderparams != null && orderparams.length > 0)
      {
        for (int i = 0; i < orderparams.length; i++)
        {
          //根据属性名获取属性
          var _property = typeof(t).getproperty(orderparams[i].propertyname);
          //创建一个访问属性的表达式
          var _propertyaccess = expression.makememberaccess(_orderparames, _property);
          var _orderbyexp = expression.lambda(_propertyaccess, _orderparames);
          string _ordername = orderparams[i].method == ordermethod.asc ? "orderby" : "orderbydescending";
          methodcallexpression resultexp = expression.call(typeof(queryable), _ordername, new type[] { typeof(t), _property.propertytype }, _list.expression, expression.quote(_orderbyexp));
          _list = _list.provider.createquery<t>(resultexp);
        }
      }
      if (number > 0) _list = _list.take(number);
      return _list;
    }
    #endregion

二、业务逻辑层

1、用户模型

ninesky.core【右键】->添加->类,输入类名user。

引用system.componentmodel.dataannotations命名空间

using system;
using system.componentmodel.dataannotations;

namespace ninesky.core
{
  /// <summary>
  /// 用户模型
  /// </summary>
  public class user
  {
    [key]
    public int userid { get; set; }

    /// <summary>
    /// 角色id
    /// </summary>
    [required(errormessage = "必须输入{0}")]
    [display(name = "角色id")]
    public int roleid { get; set; }

    /// <summary>
    /// 用户名
    /// </summary>
    [stringlength(50, minimumlength = 4, errormessage = "{0}长度为{2}-{1}个字符")]
    [display(name = "用户名")]
    public string username { get; set; }

    /// <summary>
    /// 名称【可做昵称、真实姓名等】
    /// </summary>
    [stringlength(20, errormessage = "{0}必须少于{1}个字符")]
    [display(name = "名称")]
    public string name { get; set; }

    /// <summary>
    /// 性别【0-女,1-男,2-保密】
    /// </summary>
    [required(errormessage = "必须输入{0}")]
    [range(0,2,errormessage ="{0}范围{1}-{2}")]
    [display(name = "性别")]
    public int sex { get; set; }

    /// <summary>
    /// 密码
    /// </summary>
    [datatype(datatype.password)]
    [stringlength(256, errormessage = "{0}长度少于{1}个字符")]
    [display(name = "密码")]
    public string password { get; set; }

    /// <summary>
    /// email
    /// </summary>
    [datatype(datatype.emailaddress)]
    [stringlength(50, minimumlength = 4, errormessage = "{0}长度为{2}-{1}个字符")]
    [display(name = "email")]
    public string email { get; set; }

    /// <summary>
    /// 最后登录时间
    /// </summary>
    [datatype(datatype.datetime)]
    [display(name = "最后登录时间")]
    public nullable<datetime> lastlogintime { get; set; }


    /// <summary>
    /// 最后登录ip
    /// </summary>
    [display(name = "最后登录ip")]
    public string lastloginip { get; set; }

    /// <summary>
    /// 注册时间
    /// </summary>
    [required(errormessage = "必须输入{0}")]
    [display(name = "注册时间")]
    public datetime regtime { get; set; }

    /// <summary>
    /// 角色
    /// </summary>
    public virtual role role { get; set; }

  }
}

用户名、密码和email未设置成必填是考虑到,以后可以扩展qq账号、微博账号等owin方式登录等功能,用owin登录的账号不会有这几个参数。对于用户添加和注册,可以写一个视图模型进行验证。

2、添加表映射

打开ninesky.core/nineskycontext.cs,添加users表映射(红框部分)

3、更新数据表

在【工具栏】->【工具】->nuget包管理器->程序包管理器控制台,运行命令update-database。

4、用户管理类

ninesky.core【右键】->添加->类,输入类名usermanager,类继承自basemanager<user>

引用命名空间:using ninesky.core.types; using ninesky.datalibrary;

因一般网站用户的数量肯能要较多,在显示用户列表的时候要分页显示,在数据存储层(ninesky.datalibrary)的repository类中 public iqueryable<t> findpagelist<tkey>(int pagesize, int pageindex, out int totalnumber, expression<func<t, bool>> where, expression<func<t, tkey>> order, bool asc)等分页方法,方法参数where为lambda表达式树,在usermanager类的方法中我希望动态构造表达式树,这里需要借助一个小工具linqkit。

ninesky.core->引用【右键】->管理nuget程序包。

在nuget包管理器中搜索linqkit,安装linqkit最新版本。

在usercontroller中引用命名空间using linqkit;

4.1 分页列表

添加findpagelist方法,代码如下:

/// <summary>
    /// 分页列表
    /// </summary>
    /// <param name="paginguser">分页数据</param>
    /// <param name="roleid">角色id</param>
    /// <param name="username">用户名</param>
    /// <param name="name">名称</param>
    /// <param name="sex">性别</param>
    /// <param name="email">email</param>
    /// <param name="order">排序【null(默认)-id降序,0-id升序,1-id降序,2-注册时间降序,3-注册时间升序,4-最后登录时间升序,5-最后登录时间降序】</param>
    /// <returns></returns>
    public paging<user> findpagelist(paging<user> paginguser, int? roleid, string username, string name, int? sex, string email, int? order)
    {
      //查询表达式
      var _where = predicatebuilder.true<user>();
      if (roleid != null && roleid > 0) _where = _where.and(u => u.roleid == roleid);
      if (!string.isnullorempty(username)) _where = _where.and(u => u.username.contains(username));
      if (!string.isnullorempty(name)) _where = _where.and(u => u.name.contains(name));
      if (sex != null && sex >= 0 && sex <= 2) _where = _where.and(u => u.sex == sex);
      if (!string.isnullorempty(email)) _where = _where.and(u => u.email.contains(email));
      //排序
      orderparam _orderparam;
      switch(order)
      {
        case 0://id升序
          _orderparam = new orderparam() { propertyname = "userid", method = ordermethod.asc };
          break;
        case 1://id降序
          _orderparam = new orderparam() { propertyname = "userid", method = ordermethod.desc };
          break;
        case 2://注册时间降序
          _orderparam = new orderparam() { propertyname = "regtime", method = ordermethod.asc };
          break;
        case 3://注册时间升序
          _orderparam = new orderparam() { propertyname = "regtime", method = ordermethod.desc };
          break;
        case 4://最后登录时间升序
          _orderparam = new orderparam() { propertyname = "lastlogintime", method = ordermethod.asc };
          break;
        case 5://最后登录时间降序
          _orderparam = new orderparam() { propertyname = "lastlogintime", method = ordermethod.desc };
          break;
        default://id降序
          _orderparam = new orderparam() { propertyname = "userid", method = ordermethod.desc };
          break;
      }
      paginguser.items = repository.findpagelist(paginguser.pagesize,paginguser.pageindex, out paginguser.totalnumber, _where.expand(),_orderparam).tolist();
      return paginguser;
    }

4.2 判断用户名是否存在

添加hasusername方法,代码如下

/// <summary>
    /// 用户名是否存在
    /// </summary>
    /// <param name="accounts">用户名[不区分大小写]</param>
    /// <returns></returns>
    public bool hasusername(string username)
    {
      return base.repository.iscontains(u => u.username.toupper() == username.toupper());
    }

4.3判断email是否存在

添加hasemail方法,代码如下

/// <summary>
    /// email是否存在
    /// </summary>
    /// <param name="email">email[不区分大小写]</param>
    /// <returns></returns>
    public bool hasemail(string email)
    {
      return base.repository.iscontains(u => u.email.toupper() == email.toupper());
    }

4.4 添加用户

因添加用户时,账号和email不能重复所以添加前先判断一下用户名和密码是否存在。这里用户名为空时不进行判断是因为考虑有可能以后使用可能用qq等其他方式登录。

/// <summary>
    /// 添加【返回值response.code:0-失败,1-成功,2-账号已存在,3-email已存在】
    /// </summary>
    /// <param name="user">用户</param>
    /// <returns></returns>
    public override response add(user user)
    {
      response _resp = new response();
      //账号是否存在
      if (!string.isnullorempty(user.username) && hasusername(user.username))
      {
        _resp.code = 2;
        _resp.message = "用户名已存在";
      }
      //email是否存在
      if (!string.isnullorempty(user.email) && hasusername(user.email))
      {
        _resp.code = 3;
        _resp.message = "email已存在";
      }
      if(_resp.code == 0) _resp = base.add(user);
      return _resp;
    }

三、展示层

ninesky.web/areas/control/controllers【右键】->添加->控制器。选择 mvc5 控制器 – 空, 输入控制器名称usercontroller。

在控制器中引入命名空间ninesky.core;(1)

为控制器添加身份验证[adminauthorize](2)

添加变量private rolemanager rolemanager = new rolemanager();(3)

1、用户浏览

1.1、分页列表方法

在usercontroller中添加方法pagelistjson,返回json格式的分页数据。

/// <summary>
    /// 分页列表【json】
    /// </summary>
    /// <param name="roleid">角色id</param>
    /// <param name="username">用户名</param>
    /// <param name="name">名称</param>
    /// <param name="sex">性别</param>
    /// <param name="email">email</param>
    /// <param name="pageindex">页码</param>
    /// <param name="pagesize">每页记录数</param>
    /// <param name="order">排序</param>
    /// <returns>json</returns>
    public actionresult pagelistjson(int? roleid, string username,string name,int? sex,string email,int? pagenumber, int? pagesize,int? order)
    {
      paging<user> _paginguser = new paging<core.user>();
      if (pagenumber != null && pagenumber > 0) _paginguser.pageindex = (int)pagenumber;
      if (pagesize != null && pagesize > 0) _paginguser.pagesize = (int)pagesize;
      var _paging = usermanager.findpagelist(_paginguser, roleid, username, name, sex, email, null);
      return json(new { total = _paging.totalnumber, rows = _paging.items });
    }

1.2、默认页视图

在usercontroller中添加index方法

/// <summary>
    /// 默认页
    /// </summary>
    /// <returns></returns>
    public actionresult index()
    {
      return view();
    }

在index 方法上点右键 –>添加->视图

@{
  viewbag.title = "用户管理";
}

@section sidenav{@html.partial("sidenavpartialview")}

<ol class="breadcrumb">
  <li><span class="glyphicon glyphicon-home"></span> @html.actionlink("首页", "index", "home")</li>
  <li class="active">@html.actionlink("用户管理", "index", "user")</li>
</ol>

<table id="usergrid"></table>
@section style{
  @styles.render("~/content/bootstrapplugincss")
}

@section scripts{
  @scripts.render("~/bundles/jqueryval")
  @scripts.render("~/bundles/bootstrapplugin")
  <script type="text/javascript">
    $(document).ready(function () {
      //表格
      var $table = $('#usergrid');
      $table.bootstraptable({
        showrefresh: true,
        showcolumns: true,
        pagination: true,
        sidepagination: "server",
        pagelist:"[5, 10, 20, 50, 100]",
        method: "post",
        url: "@url.action("pagelistjson")",
        columns: [
          { title: "id", field: "userid" },
          { title: "角色", field: "roleid" },
          { title: "用户名", field: "username" },
          { title: "名称", field: "name", formatter: function (value, row, index) { return "<a href='@url.action("modify", "user")/" + row.userid + "'>" + value + "</a>" } },
          { title: "性别", field: "sex" },
          { title: "email", field: "email", visible:false },
          { title: "最后登录时间", field: "lastlogintime" },
          { title: "最后登录ip", field: "lastloginip", visible:false },
          { title: "注册时间", field: "regtime",visible:false },
          { title: "操作", field: "userid", formatter: function (value) { return "<a class='btn btn-sm btn-danger' data-operation='deleteuser' data-value='" + value + "'>删除</a>" } }
        ],
        onloadsuccess: function () {
          //删除按钮
          //删除按钮结束
        }
      });
      //表格结束
    });
  </script>
}

1.3侧导航局部视图

ninesky.web/areas/control/views/user【右键】->添加->视图,输入视图名称

<div class="panel panel-default">
  <div class="panel-heading">
    <div class="panel-title"><span class="glyphicon glyphicon-user"></span> 用户管理</div>
  </div>
  <div class="panel-body">
    <div class="list-group">
      <div class="list-group-item"><span class="glyphicon glyphicon-plus"></span> @html.actionlink("添加用户", "add", "user")</div>
      <div class="list-group-item"><span class="glyphicon glyphicon-list"></span> @html.actionlink("用户管理", "index", "user")</div>
    </div>
  </div>
</div>

2、添加用户

2.1 添加用户视图模型

ninesky.web/areas/control/models【右键】->添加->“adduserviewmodel”

using system.componentmodel.dataannotations;
using system.web.mvc;

namespace ninesky.web.areas.control.models
{
  /// <summary>
  /// 添加用户视图模型类
  /// </summary>
  public class adduserviewmodel
  {
    /// <summary>
    /// 角色id
    /// </summary>
    [required(errormessage = "必须选择{0}")]
    [display(name = "角色id")]
    public int roleid { get; set; }

    /// <summary>
    /// 用户名
    /// </summary>
    [remote("canusername","user",httpmethod = "post", errormessage ="用户名已存在")]
    [stringlength(50, minimumlength = 4, errormessage = "{0}长度为{2}-{1}个字符")]
    [required(errormessage = "必须输入{0}")]
    [display(name = "用户名")]
    public string username { get; set; }

    /// <summary>
    /// 姓名【可做昵称、真实姓名等】
    /// </summary>
    [stringlength(20, errormessage = "{0}必须少于{1}个字符")]
    [display(name = "姓名")]
    public string name { get; set; }

    /// <summary>
    /// 性别【0-女,1-男,2-保密】
    /// </summary>
    [required(errormessage = "必须选择{0}")]
    [range(0, 2, errormessage = "{0}范围{1}-{2}")]
    [display(name = "性别")]
    public int sex { get; set; }

    /// <summary>
    /// 密码
    /// </summary>
    [required(errormessage = "必须输入{0}")]
    [datatype(datatype.password)]
    [stringlength(256, errormessage = "{0}长度少于{1}个字符")]
    [display(name = "密码")]
    public string password { get; set; }

    /// <summary>
    /// 确认密码
    /// </summary>
    [system.componentmodel.dataannotations.compare("password",errormessage ="两次输入的密码不一致")]
    [datatype(datatype.password)]
    [display(name = "确认密码")]
    public string confirmpassword { get; set; }

    /// <summary>
    /// email
    /// </summary>
    [required(errormessage = "必须输入{0}")]
    [datatype(datatype.emailaddress)]
    [remote("canemail", "user",httpmethod = "post", errormessage = "email已存在")]
    [stringlength(50, minimumlength = 4, errormessage = "{0}长度为{2}-{1}个字符")]
    [display(name = "email")]
    public string email { get; set; }
  }
}

模型中使用到了远程验证(remote)、属性比较(compare)等验证方式。

2.2用户名和email远程验证方法

在usercontroller中添加canusername和canemail方法

/// <summary>
    /// 用户名是否可用
    /// </summary>
    /// <param name="username">用户名</param>
    /// <returns></returns> 
    [httppost]
    public jsonresult canusername(string username)
    {
      return json(!usermanager.hasusername(username));
    }

    /// <summary>
    /// email是否存可用
    /// </summary>
    /// <param name="email">email</param>
    /// <returns></returns> 
    [httppost]
    public jsonresult canemail(string email)
    {
      return json(!usermanager.hasemail(email));
    }

2.3 添加用户页面

在usercontroller中添加add方法

/// <summary>
    /// 添加用户
    /// </summary>
    /// <returns></returns>
    public actionresult add()
    {
      //角色列表
      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 view();
    }

方法中向视图传递角色列表viewbag.roles

右键添加视图

代码如下:

@model ninesky.web.areas.control.models.adduserviewmodel

@{
  viewbag.title = "添加用户";
}

@section sidenav{@html.partial("sidenavpartialview")}

<ol class="breadcrumb">
  <li><span class="glyphicon glyphicon-home"></span> @html.actionlink("首页", "index", "home")</li>
  <li> @html.actionlink("用户管理", "index", "user")</li>
  <li class="active">@html.actionlink("添加用户", "add", "user")</li>
</ol>
@using (html.beginform()) 
{
  @html.antiforgerytoken()
  
  <div class="form-horizontal">
    <hr />
    @html.validationsummary(true, "", new { @class = "text-danger" })
    <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" } })
        @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.confirmpassword, htmlattributes: new { @class = "control-label col-md-2" })
      <div class="col-md-10">
        @html.editorfor(model => model.confirmpassword, new { htmlattributes = new { @class = "form-control" } })
        @html.validationmessagefor(model => model.confirmpassword, "", 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">
      <div class="col-md-offset-2 col-md-10">
        <input type="submit" value="添加" class="btn btn-default" />
      </div>
    </div>
  </div>
}
@scripts.render("~/bundles/jqueryval")

2.4添加处理方法

usercontroller中添加add(adduserviewmodel userviewmodel)方法

[httppost]
    [validateantiforgerytoken]
    public actionresult add(adduserviewmodel userviewmodel)
    {
      if (usermanager.hasusername(userviewmodel.username)) modelstate.addmodelerror("username","用户名已存在");
      if (usermanager.hasemail(userviewmodel.email)) modelstate.addmodelerror("email", "email已存在");
      if (modelstate.isvalid)
      {
        core.user _user = new core.user();
        _user.roleid = userviewmodel.roleid;
        _user.username = userviewmodel.username;
        _user.name = userviewmodel.name;
        _user.sex = userviewmodel.sex;
        _user.password = core.general.security.sha256(userviewmodel.password);
        _user.email = userviewmodel.email;
        _user.regtime = system.datetime.now;
        var _response = usermanager.add(_user);
        if (_response.code == 1) return view("prompt",new prompt() { title="添加用户成功",
         message="您已成功添加了用户【"+ _response.data.username+ "("+ _response.data.name + ")】",
         buttons= new list<string> {"<a href=\"" + url.action("index", "user") + "\" class=\"btn btn-default\">用户管理</a>",
         "<a href=\"" + url.action("details", "user",new { id= _response.data.userid }) + "\" class=\"btn btn-default\">查看用户</a>",
         "<a href=\"" + url.action("add", "user") + "\" class=\"btn btn-default\">继续添加</a>"} });
        else modelstate.addmodelerror("", _response.message);
      }
      //角色列表
      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 view(userviewmodel);
    } 

2.5添加成功提示

usercontroller中[右键]添加视图-prompt

@model ninesky.web.models.prompt

@{
  viewbag.title = "提示";
}

@section sidenav{@html.partial("sidenavpartialview")}

<ol class="breadcrumb">
  <li><span class="glyphicon glyphicon-home"></span> @html.actionlink("首页", "index", "home")</li>
  <li class="active"> @html.actionlink("用户管理", "index", "user")</li>
</ol>
@html.partial("promptpartialview", model)

2.6 添加提示消息局部视图

ninesky.web/areas/control/views/shared【右键】->添加->视图。视图名为promptpartialview。

代码如下:

@model ninesky.web.models.prompt

<div class="panel panel-default">
  <div class="panel-heading"><div class="panel-title">@model.title</div></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>

 运行效果

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

前几天就忙完了,中间休息了一下,顺便调整一下状态。

由于代码20多天前些了一部分,到现在有些忘记当时的想法了,今天又写了一些感觉衔接不好,有点乱。

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