完善李琦提交的通过用户指派角色功能,增加样式,格式化角色列表

This commit is contained in:
Argo-Lenovo 2016-10-28 13:36:43 +08:00
parent 26dc3fa7bc
commit 35c915c3e8
7 changed files with 139 additions and 98 deletions

View File

@ -146,3 +146,15 @@ ul.sidebar-menu {
transition: all 0.3s ease;
color: #aeb2b7;
}
/*Modal Dialog Checkbox*/
.modal-body .checkbox {
padding: 5px;
margin-top: 0;
margin-bottom: 0;
}
.modal-body .checkbox label input[type='checkbox'] {
margin-right: 6px;
top: 2px;
}

View File

@ -214,22 +214,27 @@
};
Role = {};
Role.getRolesByUserId = function (userId, callback) {
var processRolesData = function (options) {
var data = $.extend({ data: { type: "" }, method: "POST", Id: "" }, options);
$.ajax({
url: '../api/Roles/' + userId,
data: { "": "user" },
type: 'POST',
url: '../api/Roles/' + data.Id,
data: data.data,
type: data.method,
success: function (result) {
callback(result);
if ($.isFunction(data.callback)) data.callback(result);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
callback();
if ($.isFunction(data.callback)) data.callback(false);
}
});
}
Role = {};
Role.getRolesByUserId = function (userId, callback) {
processRolesData({ Id: userId, callback: callback, data: { type: "user" } });
};
Role.getRolesByGroupId = function (groupId) {
processRolesData({ Id: groupId, callback: callback, data: { type: "group" } });
};
//查询菜单对应角色
@ -248,17 +253,7 @@
};
Role.saveRolesByUserId = function (userId, roleIds, callback) {
$.ajax({
url: '../api/Roles/' + userId,
data: { "roleIds": roleIds,"type":"user" },
type: 'PUT',
success: function (result) {
callback(result);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
callback();
}
});
processRolesData({ Id: userId, callback: callback, method: "PUT", data: { type: "user", roleIds: roleIds } });
}
//保存菜单对应角色

View File

@ -2,6 +2,7 @@
using Bootstrap.DataAccess;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace Bootstrap.Admin.Controllers
@ -24,15 +25,22 @@ namespace Bootstrap.Admin.Controllers
/// <param name="id"></param>
/// <returns></returns>
[HttpPost]
public IEnumerable<Role> Post(int id, [FromBody]string value)
public IEnumerable<Role> Post(int id, [FromBody]JObject value)
{
if (value == "user")
var ret = new List<Role>();
dynamic json = value;
switch ((string)json.type)
{
return RoleHelper.RetrieveRolesByUserId(id.ToString());
}
else if(value == "menu")
{
return RoleHelper.RetrieveRolesByMenuId(id.ToString());
case "user":
ret = RoleHelper.RetrieveRolesByUserId(id).ToList();
break;
case "group":
ret = RoleHelper.RetrieveRolesByGroupId(id).ToList();
break;
case "menu"
ret = RoleHelper.RetrieveRolesByMenuId(id.ToString());
default:
break;
}
else
{
@ -47,13 +55,23 @@ namespace Bootstrap.Admin.Controllers
[HttpPut]
public bool Put(int id, [FromBody]JObject value)
{
var ret = false;
dynamic json = value;
string roleIds = json.roleIds;
if (json.type == "user")
return RoleHelper.SaveRolesByUserId(id, roleIds);
if (json.type == "menu")
return RoleHelper.SavaRolesByMenuId(id,roleIds);
return false;
switch ((string)json.type)
{
case "user":
ret = RoleHelper.SaveRolesByUserId(id, roleIds);
break;
case "group":
ret = RoleHelper.SaveRolesByGroupId(id, roleIds);
break;
case "menu":
ret = RoleHelper.SavaRolesByMenuId(id, roleIds);
default:
break;
}
return ret;
}
/// <summary>
///

View File

@ -16,11 +16,7 @@
Role.getRolesByUserId(row.ID, function (roles) {
$("#dialogRole .modal-title").text($.format('{0}-角色授权窗口', row.DisplayName));
var data = $.map(roles, function (element, index) {
if (element.IsSelect == 1) {
return $.format('<div class="checkbox"><label><input type="checkbox" value="{0}" checked="checked">{1}</label></div>', element.ID, element.RoleName);
} else if (element.IsSelect == 0) {
return $.format('<div class="checkbox"><label><input type="checkbox" value="{0}">{1}</label></div>', element.ID, element.RoleName);
}
return $.format('<div class="checkbox col-lg-3 col-xs-4"><label title="{3}"><input type="checkbox" value="{0}" {2}>{1}</label></div>', element.ID, element.RoleName, element.Checked, element.Description);
}).join('');
$('#dialogRole form').html(data);
$('#dialogRole').modal('show');

View File

@ -15,8 +15,8 @@
/// </summary>
public string Description { get; set; }
/// <summary>
/// 获取/设置 用户角色状态
/// 获取/设置 用户角色关联状态 checked 标示已经关联 '' 标示未关联
/// </summary>
public int IsSelect { get; set; }
public string Checked { get; set; }
}
}

View File

@ -13,8 +13,12 @@ using System.Linq;
namespace Bootstrap.DataAccess
{
/// <summary>
///
/// </summary>
public class RoleHelper
{
// UNDONE: 两个缓存考虑可以共用,待完善
private const string RoleDataKey = "RoleData-CodeRoleHelper";
private const string RoleUserIDDataKey = "RoleData-CodeRoleHelper-";
private const string RoleNavigationIDDataKey = "RoleData-CodeRoleHelper-Navigation";
@ -54,72 +58,81 @@ namespace Bootstrap.DataAccess
/// 保存用户角色关系
/// </summary>
/// <param name="id"></param>
/// <param name="value"></param>
/// <param name="roleIds"></param>
/// <returns></returns>
public static bool SaveRolesByUserId(int id, string value)
public static bool SaveRolesByUserId(int id, string roleIds)
{
var ret = false;
DataTable dt = new DataTable();
dt.Columns.Add("UserID", typeof(int));
dt.Columns.Add("RoleID", typeof(int));
//判断用户是否选定角色
if (!string.IsNullOrEmpty(value))
if (!string.IsNullOrEmpty(roleIds))
{
string[] roleIDs = value.Split(',');
foreach (string roleID in roleIDs)
roleIds.Split(',').ToList().ForEach(roleId =>
{
DataRow row = dt.NewRow();
row["UserID"] = id;
row["RoleID"] = roleID;
dt.Rows.Add(row);
dt.Rows.Add(id, roleId);
});
}
}
using (TransactionPackage transaction = DBAccessManager.SqlDBAccess.BeginTransaction())
{
try
{
// delete user from config table
string sql = "delete from UserRole where UserID = @UserID;";
using (DbCommand cmd = DBAccessManager.SqlDBAccess.CreateCommand(CommandType.Text, sql))
{
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@UserID", id, ParameterDirection.Input));
using (TransactionPackage transaction = DBAccessManager.SqlDBAccess.BeginTransaction())
{
DBAccessManager.SqlDBAccess.ExecuteNonQuery(cmd, transaction);
// insert batch data into config table
using (SqlBulkCopy bulk = new SqlBulkCopy((SqlConnection)transaction.Transaction.Connection, SqlBulkCopyOptions.Default, (SqlTransaction)transaction.Transaction))
{
bulk.BatchSize = 1000;
bulk.DestinationTableName = "UserRole";
bulk.ColumnMappings.Add("UserID", "UserID");
bulk.ColumnMappings.Add("RoleID", "RoleID");
bool ret = true;
try
{
DBAccessManager.SqlDBAccess.ExecuteNonQuery(cmd, transaction);
bulk.WriteToServer(dt);
transaction.CommitTransaction();
}
}
ret = true;
ClearCache();
}
catch (Exception ex)
{
ret = false;
ExceptionManager.Publish(ex);
transaction.RollbackTransaction();
}
}
return ret;
}
}
}
/// <summary>
///
/// </summary>
/// <param name="id"></param>
/// <param name="value"></param>
/// <returns></returns>
public static bool SaveRolesByGroupId(int id, string value)
{
return true;
}
/// <summary>
/// 查询某个用户所拥有的角色
/// </summary>
/// <returns></returns>
public static IEnumerable<Role> RetrieveRolesByUserId(string userId)
public static IEnumerable<Role> RetrieveRolesByUserId(int userId)
{
string sql = "select *,case when (ID in( select RoleID from UserRole where UserID=@UserID)) then 1 else 0 end as IsSelect from Roles";
string k = string.Format("{0}{1}", RoleUserIDDataKey, userId);
var ret = CacheManager.GetOrAdd(k, CacheSection.RetrieveIntervalByKey(RoleUserIDDataKey), key =>
return CacheManager.GetOrAdd(k, CacheSection.RetrieveIntervalByKey(RoleUserIDDataKey), key =>
{
List<Role> Roles = new List<Role>();
DbCommand cmd = DBAccessManager.SqlDBAccess.CreateCommand(CommandType.Text, sql);
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@UserID", userId, ParameterDirection.Input));
string sql = "select r.ID, r.RoleName, r.[Description], case ur.RoleID when r.ID then 'checked' else '' end [status] from Roles r left join UserRole ur on r.ID = ur.RoleID and UserID = @UserID";
try
{
DbCommand cmd = DBAccessManager.SqlDBAccess.CreateCommand(CommandType.Text, sql);
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@UserID", userId, ParameterDirection.Input));
using (DbDataReader reader = DBAccessManager.SqlDBAccess.ExecuteReader(cmd))
{
while (reader.Read())
@ -129,7 +142,7 @@ namespace Bootstrap.DataAccess
ID = (int)reader[0],
RoleName = (string)reader[1],
Description = (string)reader[2],
IsSelect = (int)reader[3]
Checked = (string)reader[3]
});
}
}
@ -137,7 +150,15 @@ namespace Bootstrap.DataAccess
catch (Exception ex) { ExceptionManager.Publish(ex); }
return Roles;
}, CacheSection.RetrieveDescByKey(RoleUserIDDataKey));
return ret;
}
/// <summary>
///
/// </summary>
/// <param name="groupId"></param>
/// <returns></returns>
public static IEnumerable<Role> RetrieveRolesByGroupId(int groupId)
{
return new List<Role>();
}
/// <summary>
/// 删除角色表
@ -163,7 +184,6 @@ namespace Bootstrap.DataAccess
}
return ret;
}
/// <summary>
/// 保存新建/更新的角色信息
/// </summary>
@ -290,9 +310,9 @@ namespace Bootstrap.DataAccess
}
// 更新缓存
private static void ClearCache()
private static void ClearCache(string cacheKey = null)
{
CacheManager.Clear(key => key.Contains("RoleData-"));
CacheManager.Clear(key => string.IsNullOrEmpty(cacheKey) || key == cacheKey);
}
}
}

View File

@ -48,7 +48,7 @@ namespace Bootstrap.DataAccess.Tests
[TestMethod()]
public void RetrieveRolesByUserIdTest()
{
var result = RoleHelper.RetrieveRolesByUserId("1");
var result = RoleHelper.RetrieveRolesByUserId(1);
Assert.IsTrue(result.Count() >= 0, "用户查询角色关系失败!");
}
[TestMethod()]