You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

1814 lines
66 KiB

using System;
using System.Collections;
using System.Web.Security;
using System.Web.UI;
using System.Reflection;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Linq;
using System.Web;
using System.Data.Entity;
using CK.SCP.Models;
using CK.SCP.Models.AppBoxEntity;
using FineUI;
using System.IO;
using System.Transactions;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using CK.SCP.Models.ScpEntity;
using CK.SCP.Controller;
using CK.SCP.Utils;
using System.Net;
using System.Text;
using NPOI.XSSF.UserModel;
using NPOI.SS.Util;
namespace SCP
{
public class PageBase : System.Web.UI.Page
{
#region 只读静态变量
// Session key
private static readonly string SK_ONLINE_UPDATE_TIME = "OnlineUpdateTime";
//private static readonly string SK_USER_ROLE_ID = "UserRoleId";
private static readonly string CHECK_POWER_FAIL_PAGE_MESSAGE = "您无权访问此页面!";
private static readonly string CHECK_POWER_FAIL_ACTION_MESSAGE = "您无权进行此操作!";
private static readonly string CHECK_POWER_FAIL_ACTION = "只能删除自己发布的信息!";
#endregion
#region 实体上下文
public static AppBoxContext DB
{
get
{
// http://stackoverflow.com/questions/6334592/one-dbcontext-per-request-in-asp-net-mvc-without-ioc-container
if (!HttpContext.Current.Items.Contains("__AppBoxContext"))
{
HttpContext.Current.Items["__AppBoxContext"] = EntitiesFactory.CreateAppBoxInstance();
}
return HttpContext.Current.Items["__AppBoxContext"] as AppBoxContext;
}
}
public static ScpEntities SCPDB
{
get
{
// http://stackoverflow.com/questions/6334592/one-dbcontext-per-request-in-asp-net-mvc-without-ioc-container
if (!HttpContext.Current.Items.Contains("__SCPEntitiesContext"))
{
HttpContext.Current.Items["__SCPEntitiesContext"] = EntitiesFactory.CreateScpInstance();
}
return HttpContext.Current.Items["__SCPEntitiesContext"] as ScpEntities;
}
}
#endregion
#region 浏览权限
/// <summary>
/// 本页面的浏览权限,空字符串表示本页面不受权限控制
/// </summary>
public virtual string ViewPower
{
get { return String.Empty; }
}
#endregion
#region 页面初始化
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
// 此用户是否有访问此页面的权限
if (!CheckPowerView())
{
CheckPowerFailWithPage();
return;
}
// 设置主题
if (PageManager.Instance != null)
{
PageManager.Instance.Theme = (Theme)Enum.Parse(typeof(Theme), ConfigHelper.Theme, true);
}
UpdateOnlineUser(User.Identity.Name);
// 设置页面标题
Page.Title = ConfigHelper.Title;
}
#endregion
#region 请求参数
/// <summary>
/// 获取查询字符串中的参数值
/// </summary>
protected string GetQueryValue(string queryKey)
{
return Request.QueryString[queryKey];
}
/// <summary>
/// 获取查询字符串中的参数值
/// </summary>
protected int GetQueryIntValue(string queryKey)
{
int queryIntValue = -1;
try
{
if (Request.QueryString[queryKey] != null)
{
queryIntValue = Convert.ToInt32(Request.QueryString[queryKey]);
}
}
catch (Exception)
{
// TODO
}
return queryIntValue;
}
public void BindVenderByUser(DropDownList p_dl)
{
var _entity = CurrentUser.VenderList;
var _p = CurrentUser.FactoryList;
if (_entity.Count>0)
{
var ls = SCP_TB_VENDER_CONTROLLER.Getlist(_entity,_p);
var lsVender = ls;
lsVender.ForEach(p =>
{
p.VendName = string.Format("{0}({1})", p.VendName, p.VendId);
});
p_dl.DataSource = lsVender;
p_dl.DataTextField = "VendName";
p_dl.DataValueField = "VendId";
p_dl.DataBind();
p_dl.Items.Insert(0, new FineUI.ListItem("--无供应商--", string.Empty));
}
}
protected void BindVender(DropDownList p_dl)
{
var _entity = CurrentUser.FactoryList;
if (_entity.Count > 0)
{
var ls = SCP_TB_VENDER_CONTROLLER.GetVenderList(_entity);
var lsVender = ls;
if (_entity.Contains("CNS") || _entity.Contains("NAP"))
{
lsVender = ls.Where(p => p.VendId.Substring(0, 1) == "R" || p.VendId.Substring(0, 1) == "E").ToList();
}
lsVender.ForEach(p =>
{
p.VendName = string.Format("{0}({1})", p.VendName, p.VendId);
});
p_dl.DataSource = lsVender;
p_dl.DataTextField = "VendName";
p_dl.DataValueField = "VendId";
p_dl.DataBind();
p_dl.Items.Insert(0, new FineUI.ListItem("--无供应商--", string.Empty));
//}
}
}
protected string HttpPost(string Url, string postDataStr)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr);
Stream myRequestStream = request.GetRequestStream();
StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));
myStreamWriter.Write(postDataStr);
myStreamWriter.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
string retString = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close();
return retString;
}
#endregion
#region 表格相关
protected int GetSelectedDataKeyID(Grid grid)
{
int id = -1;
int rowIndex = grid.SelectedRowIndex;
if (rowIndex >= 0)
{
id = Convert.ToInt32(grid.DataKeys[rowIndex][0]);
}
return id;
}
protected string GetSelectedDataKey(Grid grid, int dataIndex)
{
string data = String.Empty;
int rowIndex = grid.SelectedRowIndex;
if (rowIndex >= 0)
{
data = grid.DataKeys[rowIndex][dataIndex].ToString();
}
return data;
}
/// <summary>
/// 获取表格选中项DataKeys的第一个值,并转化为整型列表
/// </summary>
/// <param name="grid"></param>
/// <returns></returns>
protected List<int> GetSelectedDataKeyIDs(Grid grid)
{
List<int> ids = new List<int>();
foreach (int rowIndex in grid.SelectedRowIndexArray)
{
ids.Add(Convert.ToInt32(grid.DataKeys[rowIndex][0]));
}
return ids;
}
protected List<string> GetSelectedDataKeyIDss(Grid grid)
{
List<string> ids = new List<string>();
foreach (int rowIndex in grid.SelectedRowIndexArray)
{
ids.Add(grid.DataKeys[rowIndex][1].ToString());
}
return ids;
}
#endregion
#region 获取aspx数据后
/// <summary>
///
/// </summary>
/// <param name="p_grid">列表</param>
/// <param name="p_str">显示列表字段名称</param>
protected void IsPriceVisible(Grid p_grid, params string[] p_str)
{
if (CurrentUser.RoleList.Contains("查看价格"))
{
foreach (var itm in p_grid.Columns)
{
if (p_str.Contains(itm.HeaderText))
{
itm.Hidden = false;
}
}
}
}
protected void IsPriceEdit(Grid p_grid, params string[] p_str)
{
if (CurrentUser.RoleList.Contains("查看价格"))
{
foreach (var itm in p_grid.Columns)
{
if (p_str.Contains(itm.HeaderText))
{
itm.Hidden = false;
itm.Enabled = false;
}
}
}
}
public void UpdateDataRow<T>(Dictionary<string, object> rowDict, T entity)
{
var peroperties = entity.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (var property in peroperties)
{
foreach (KeyValuePair<string, object> row in rowDict.Where(row => row.Key == property.Name))
{
property.SetValue(entity, ConverToType(row.Value, property.PropertyType), null);
}
}
}
// 删除选中行的脚本
public string GetDeleteScript(FineUI.Grid TheGrid)
{
string confirmScript = Confirm.GetShowReference("删除选中行?", String.Empty, MessageBoxIcon.Question,
TheGrid.GetDeleteSelectedRowsReference(), String.Empty);
return String.Format("F.defer(function(){{{0}}},100);", confirmScript);
//return Confirm.GetShowReference("保存时,当前行将在服务器真正删除。删除请点确认", "删除选中行?", MessageBoxIcon.Question, TheGrid.GetDeleteSelectedRowsReference(), String.Empty);
// (FineUI v6.0更新:必须加上延迟,否则弹出框会阻止事件向上传播,导致不能选中单元格!!) 现在是4.2
//return $"F.defer(function(){{{confirmScript}}},100);";
}
private static object ConverToType(object value, Type convertsionType)
{
object returnValue = "";
try
{
if (convertsionType.IsGenericType && convertsionType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
if (value != null && value != DBNull.Value && value.ToString() != "" && value.ToString().Length > 0)
{
var nullableConverter = new NullableConverter(convertsionType);
convertsionType = nullableConverter.UnderlyingType;
returnValue = Convert.ChangeType(value, convertsionType);
}
else
{
returnValue = null;
}
}
else
{
if (value != null && value != DBNull.Value && value.ToString() != "" && value.ToString().Length > 0)
{
if (value.ToString().IndexOf("%", System.StringComparison.Ordinal) ==
value.ToString().Length - 1)
{
switch (convertsionType.ToString())
{
case "System.Decimal":
returnValue = Convert.ToDecimal(value.ToString().Replace("%", "")) / 100;
break;
case "System.Double":
returnValue = Convert.ToDecimal(value.ToString().Replace("%", "")) / 100;
break;
case "System.Single":
returnValue = Convert.ToDecimal(value.ToString().Replace("%", "")) / 100;
break;
}
}
else if (value.ToString() == "-")
{
returnValue = 0;
}
else
{
returnValue = Convert.ChangeType(value, convertsionType);
if (convertsionType.FullName == "System.Decimal")
returnValue = Math.Round((decimal)returnValue, 5);
if (convertsionType.FullName == "System.String")
returnValue = returnValue.ToString().TrimEnd();
}
}
else
{
returnValue = GetReturnValue(convertsionType);
}
}
}
catch
{
returnValue = GetReturnValue(convertsionType);
}
return returnValue;
}
private static object GetReturnValue(Type convertsionType)
{
object returnValue;
switch (convertsionType.ToString())
{
case "System.Guid":
returnValue = Guid.NewGuid();
break;
case "System.DateTime":
returnValue = DateTime.Now;
break;
case "System.Decimal":
returnValue = 0m;
break;
case "System.Double":
returnValue = 0.0;
break;
case " System.UInt16":
returnValue = 0;
break;
case " System.UInt32":
returnValue = 0;
break;
case " System.UInt64":
returnValue = 0;
break;
case "System.Int32":
returnValue = 0;
break;
case "System.Int16":
returnValue = 0;
break;
case "System.Int64":
returnValue = 0;
break;
case "System.String":
returnValue = "";
break;
case "System.Single":
returnValue = 0.0f;
break;
default:
returnValue = "";
break;
}
return returnValue;
}
#endregion
#region EF相关
// 排序
protected IQueryable<T> Sort<T>(IQueryable<T> q, FineUI.Grid grid)
{
return q.SortBy(grid.SortField + " " + grid.SortDirection);
}
protected IQueryable<T> Sort<T>(IQueryable<T> q, FineUI.Grid grid,string p_asc)
{
return q.SortBy(grid.SortField,p_asc);
}
// 排序后分页
protected IQueryable<T> SortAndPage<T>(IQueryable<T> q, FineUI.Grid grid)
{
if (grid.PageIndex >= grid.PageCount && grid.PageCount >= 1)
{
grid.PageIndex = grid.PageCount - 1;
}
return Sort(q, grid).Skip(grid.PageIndex * grid.PageSize).Take(grid.PageSize);
}
protected IQueryable<T> SortAndPage<T>(IQueryable<T> q, FineUI.Grid grid,string p_asc)
{
if (grid.PageIndex >= grid.PageCount && grid.PageCount >= 1)
{
grid.PageIndex = grid.PageCount - 1;
}
return Sort(q, grid,p_asc).Skip(grid.PageIndex * grid.PageSize).Take(grid.PageSize);
}
// 附加实体到数据库上下文中(首先在Local中查找实体是否存在,不存在才Attach,否则会报错)
// http://patrickdesjardins.com/blog/entity-framework-4-3-an-object-with-the-same-key-already-exists-in-the-objectstatemanager
protected T Attach<T>(int keyID) where T : class, IKeyID, new()
{
T t = DB.Set<T>().Local.Where(x => x.ID == keyID).FirstOrDefault();
if (t == null)
{
t = new T { ID = keyID };
DB.Set<T>().Attach(t);
}
return t;
}
// 向现有实体集合中添加新项
protected void AddEntities<T>(ICollection<T> existItems, int[] newItemIDs) where T : class, IKeyID, new()
{
foreach (int roleID in newItemIDs)
{
T t = Attach<T>(roleID);
existItems.Add(t);
}
}
// 替换现有实体集合中的所有项
// http://stackoverflow.com/questions/2789113/entity-framework-update-entity-along-with-child-entities-add-update-as-necessar
protected void ReplaceEntities<T>(ICollection<T> existEntities, int[] newEntityIDs)
where T : class, IKeyID, new()
{
if (newEntityIDs.Length == 0)
{
existEntities.Clear();
}
else
{
int[] tobeAdded = newEntityIDs.Except(existEntities.Select(x => x.ID)).ToArray();
int[] tobeRemoved = existEntities.Select(x => x.ID).Except(newEntityIDs).ToArray();
AddEntities<T>(existEntities, tobeAdded);
existEntities.Where(x => tobeRemoved.Contains(x.ID)).ToList().ForEach(e => existEntities.Remove(e));
//foreach (int roleID in tobeRemoved)
//{
// existEntities.Remove(existEntities.Single(r => r.ID == roleID));
//}
}
}
// http://patrickdesjardins.com/blog/validation-failed-for-one-or-more-entities-see-entityvalidationerrors-property-for-more-details-2
// ((System.Data.Entity.Validation.DbEntityValidationException)$exception).EntityValidationErrors
#endregion
#region 在线用户相关
protected void UpdateOnlineUser(string username)
{
DateTime now = DateTime.Now;
object lastUpdateTime = Session[SK_ONLINE_UPDATE_TIME];
if (lastUpdateTime == null || (Convert.ToDateTime(lastUpdateTime).Subtract(now).TotalMinutes > 5))
{
// 记录本次更新时间
Session[SK_ONLINE_UPDATE_TIME] = now;
Online online = DB.Onlines.Where(o => o.User.Name == username).FirstOrDefault();
if (online != null)
{
online.UpdateTime = now;
DB.SaveChanges();
}
}
}
protected void RegisterOnlineUser(User user)
{
Online online = DB.Onlines.Where(o => o.User.ID == user.ID).FirstOrDefault();
// 如果不存在,就创建一条新的记录
if (online == null)
{
online = new Online();
DB.Onlines.Add(online);
}
DateTime now = DateTime.Now;
online.User = user;
online.IPAdddress = Request.UserHostAddress;
online.LoginTime = now;
online.UpdateTime = now;
DB.SaveChanges();
// 记录本次更新时间
Session[SK_ONLINE_UPDATE_TIME] = now;
}
protected User CurrentUser
{
get
{
if (Session["CurrentUser"] == null)
{
User _currentUser = new User();
if (!string.IsNullOrEmpty(User.Identity.Name))
{
_currentUser = DB.Users.Where(itm => itm.Name == User.Identity.Name).FirstOrDefault();
var _factoryList = DB.Users.Where(itm => itm.Name == User.Identity.Name).FirstOrDefault().TA_FACTORY.Select(p => p.FactoryId).ToList();
var _siteList = DB.Users.Where(itm => itm.Name == User.Identity.Name).FirstOrDefault().TA_FACTORY.Select(p => p.ErpSite).ToList();
_currentUser.RoleList = _currentUser.Roles.Select(p => p.Name).ToList();
var _userVerders = DB.VenderUsers.Where(p => p.UserId == _currentUser.ID).Select(p => p.VenderId).ToList();
_currentUser.FactoryList = _factoryList;
_currentUser.SubSiteList = _siteList;
_currentUser.VenderList = _userVerders;
_currentUser.ConfigList = new Dictionary<string, string>();
if (_currentUser.FactoryList.Count > 0)
{
_currentUser.UsedDomain = string.IsNullOrEmpty(_currentUser.Remark) ? _currentUser.FactoryList.FirstOrDefault() :_currentUser.Remark.Trim();
}
if (_currentUser.FactoryList.Count > 0)
{
if (SCPDB.TA_FACTORY_CONFIG != null)
{
var _configList = SCPDB.TA_FACTORY_CONFIG.Where(p => _currentUser.FactoryList.Contains(p.FactoryId)).Select(p => p.ConfigId);
if (_configList != null && _configList.Count() > 0)
{
var _ls = _configList.Distinct();
var _list = SCPDB.TA_CONFIG.Where(p => _ls.Contains(p.UID) && p.State > 100).ToList();
Dictionary<string, string> _dic = new Dictionary<string, string>();
_list.ForEach(p =>
{
_dic.Add(p.ParamName, p.ParamValue);
}
);
_currentUser.ConfigList = _dic;
}
}
}
}
Session["CurrentUser"] = _currentUser;
}
return (User)Session["CurrentUser"];
}
}
//public string GetNameByKey(string p_description,string p_key)
//{
// string value = string.Empty;
// if (Session["LanguageResource"] == null)
// {
// Dictionary<string, string> _dic = new Dictionary<string, string>();
// var ret = Controller.SCP_TA_LANGUAGE_CONTROLLER.Get_TA_LANGUAGE_List(new TA_LANGUAGE());
// if (ret.State == ReturnStatus.Succeed)
// {
// var list = ret.Result;
// list.ForEach(p => _dic.Add(p.GUID, p.CH));
// Session["LanguageResource"] =_dic;
// if (_dic.ContainsKey(p_key))
// {
// value = _dic[p_key];
// }
// }
// }
// else
// {
// var _dic = Session["LanguageResource"] as Dictionary<string, string>;
// if (_dic.ContainsKey(p_key))
// {
// value= _dic[p_key];
// }
// }
// return value;
//}
#region 语言缓存列表
public string GetNameByKey(string p_key)
{
string value = p_key;
if (Session["LanguageList"] != null)
{
var _list = Session["LanguageList"] as List<V_TA_LANGUAGE>;
var list = _list.Where(itm => itm.CH == p_key);
if (list.Count() > 0)
{
if (list.FirstOrDefault() != null)
{
value = list.FirstOrDefault().LAN;
}
}
}
return value;
}
#endregion
/// <summary>
/// 在线人数
/// </summary>
/// <returns></returns>
protected int GetOnlineCount()
{
DateTime lastM = DateTime.Now.AddMinutes(-15);
return DB.Onlines.Where(o => o.UpdateTime > lastM).Count();
}
#endregion
#region 当前登录用户信息
// http://blog.163.com/zjlovety@126/blog/static/224186242010070024282/
// http://www.cnblogs.com/gaoshuai/articles/1863231.html
/// <summary>
/// 当前登录用户的角色列表
/// </summary>
/// <returns></returns>
protected List<int> GetIdentityRoleIDs()
{
List<int> roleIDs = new List<int>();
if (User.Identity.IsAuthenticated)
{
FormsAuthenticationTicket ticket = ((FormsIdentity)User.Identity).Ticket;
string userData = ticket.UserData;
foreach (string roleID in userData.Split(','))
{
if (!String.IsNullOrEmpty(roleID))
{
roleIDs.Add(Convert.ToInt32(roleID));
}
}
}
return roleIDs;
}
/// <summary>
/// 当前登录用户名
/// </summary>
/// <returns></returns>
protected string GetIdentityName()
{
if (User.Identity.IsAuthenticated)
{
return User.Identity.Name;
}
return String.Empty;
}
/// <summary>
/// 创建表单验证的票证并存储在客户端Cookie中
/// </summary>
/// <param name="userName">当前登录用户名</param>
/// <param name="roleIDs">当前登录用户的角色ID列表</param>
/// <param name="isPersistent">是否跨浏览器会话保存票证</param>
/// <param name="expiration">过期时间</param>
protected void CreateFormsAuthenticationTicket(string userName, string roleIDs, bool isPersistent,
DateTime expiration,string p_domain)
{
// 创建Forms身份验证票据
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
userName, // 与票证关联的用户名
DateTime.Now, // 票证发出时间
expiration, // 票证过期时间
isPersistent, // 如果票证将存储在持久性 Cookie 中(跨浏览器会话保存),则为 true;否则为 false。
roleIDs // 存储在票证中的用户特定的数据
);
// 对Forms身份验证票据进行加密,然后保存到客户端Cookie中
string hashTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashTicket);
cookie.HttpOnly = true;
// 1. 关闭浏览器即删除(Session Cookie):DateTime.MinValue
// 2. 指定时间后删除:大于 DateTime.Now 的某个值
// 3. 删除Cookie:小于 DateTime.Now 的某个值
//HttpCookie userdomain = new HttpCookie("Domain", p_domain);
//userdomain.HttpOnly = true;
if (isPersistent)
{
cookie.Expires = expiration;
//userdomain.Expires = expiration;
}
else
{
cookie.Expires = DateTime.MinValue;
//userdomain.Expires = DateTime.MinValue;
}
Response.Cookies.Add(cookie);
//Response.Cookies.Add(userdomain);
}
#endregion
#region 权限检查
/// <summary>
/// 检查当前用户是否拥有当前页面的浏览权限
/// 页面需要先定义ViewPower属性,以确定页面与某个浏览权限的对应关系
/// </summary>
/// <returns></returns>
protected bool CheckPowerView()
{
return CheckPower(ViewPower);
}
/// <summary>
/// 检查当前用户是否拥有某个权限
/// </summary>
/// <param name="powerType"></param>
/// <returns></returns>
protected bool CheckPower(string powerName)
{
// 如果权限名为空,则放行
if (String.IsNullOrEmpty(powerName))
{
return true;
}
// 当前登陆用户的权限列表
List<string> rolePowerNames = GetRolePowerNames();
if (rolePowerNames.Contains(powerName))
{
return true;
}
return false;
}
protected List<string> GetRolePowerNames()
{
// 将用户拥有的权限列表保存在Session中,这样就避免每个请求多次查询数据库
if (Session["UserPowerList"] == null)
{
List<string> rolePowerNames = new List<string>();
// 超级管理员拥有所有权限
if (GetIdentityName() == "admin")
{
rolePowerNames = DB.Powers.Select(p => p.Name).ToList();
}
else
{
List<int> roleIDs = GetIdentityRoleIDs();
foreach (var role in DB.Roles.Include(r => r.Powers).Where(r => roleIDs.Contains(r.ID)))
{
foreach (var power in role.Powers)
{
if (!rolePowerNames.Contains(power.Name))
{
rolePowerNames.Add(power.Name);
}
}
}
}
Session["UserPowerList"] = rolePowerNames;
}
return (List<string>)Session["UserPowerList"];
}
#endregion
#region 权限相关
protected void CheckPowerFailWithPage()
{
Response.Write(CHECK_POWER_FAIL_PAGE_MESSAGE);
Response.End();
}
protected void CheckPowerFailWithButton(FineUI.Button btn)
{
btn.Enabled = false;
btn.ToolTip = CHECK_POWER_FAIL_ACTION_MESSAGE;
}
protected void CheckPowerFailWithButtonHidden(FineUI.Button btn)
{
btn.Visible = false;
btn.ToolTip = CHECK_POWER_FAIL_ACTION_MESSAGE;
}
protected void CheckPowerFailWithLinkButtonField(FineUI.Grid grid, string columnID)
{
FineUI.LinkButtonField btn = grid.FindColumn(columnID) as FineUI.LinkButtonField;
btn.Enabled = false;
btn.ToolTip = CHECK_POWER_FAIL_ACTION_MESSAGE;
}
protected void CheckPowerFailWithWindowField(FineUI.Grid grid, string columnID)
{
FineUI.WindowField btn = grid.FindColumn(columnID) as FineUI.WindowField;
btn.Enabled = false;
btn.ToolTip = CHECK_POWER_FAIL_ACTION_MESSAGE;
}
protected void CheckPowerFailWithAlert()
{
PageContext.RegisterStartupScript(Alert.GetShowInTopReference(CHECK_POWER_FAIL_ACTION_MESSAGE));
}
protected void CheckPowerFailWithAlert1()
{
PageContext.RegisterStartupScript(Alert.GetShowInTopReference(CHECK_POWER_FAIL_ACTION));
}
protected void CheckPowerWithButton(string powerName, FineUI.Button btn)
{
if (!CheckPower(powerName))
{
CheckPowerFailWithButton(btn);
}
}
protected void CheckPowerWithButtonHidden(string powerName, FineUI.Button btn)
{
if (!CheckPower(powerName))
{
CheckPowerFailWithButtonHidden(btn);
}
}
protected void CheckPowerWithLinkButtonField(string powerName, FineUI.Grid grid, string columnID)
{
if (!CheckPower(powerName))
{
CheckPowerFailWithLinkButtonField(grid, columnID);
}
}
protected void CheckPowerWithWindowField(string powerName, FineUI.Grid grid, string columnID)
{
if (!CheckPower(powerName))
{
CheckPowerFailWithWindowField(grid, columnID);
}
}
/// <summary>
/// 为删除Grid中选中项的按钮添加提示信息
/// </summary>
/// <param name="btn"></param>
/// <param name="grid"></param>
protected void ResolveDeleteButtonForGrid(FineUI.Button btn, Grid grid)
{
ResolveDeleteButtonForGrid(btn, grid, "确定要删除选中的{0}项记录吗?");
}
protected void ResolveDeleteButtonForGrid(FineUI.Button btn, Grid grid, string confirmTemplate)
{
ResolveDeleteButtonForGrid(btn, grid, "请至少应该选择一项记录!", confirmTemplate);
}
protected void ResolveDeleteButtonForGrid(FineUI.Button btn, Grid grid, string noSelectionMessage,
string confirmTemplate)
{
// 点击删除按钮时,至少选中一项
btn.OnClientClick = grid.GetNoSelectionAlertInParentReference(noSelectionMessage);
btn.ConfirmText = String.Format(confirmTemplate,
"&nbsp;<span class=\"highlight\"><script>" + grid.GetSelectedCountReference() + "</script></span>&nbsp;");
btn.ConfirmTarget = Target.Top;
}
#endregion
#region 产品版本
public string GetProductVersion()
{
Version v = Assembly.GetExecutingAssembly().GetName().Version;
return String.Format("{0}.{1}", v.Major, v.Minor);
}
#endregion
#region 隐藏字段相关
/// <summary>
/// 从隐藏字段中获取选择的全部ID列表
/// </summary>
/// <param name="hfSelectedIDS"></param>
/// <returns></returns>
public List<int> GetSelectedIDsFromHiddenField(FineUI.HiddenField hfSelectedIDS)
{
JArray idsArray = new JArray();
string currentIDS = hfSelectedIDS.Text.Trim();
if (!String.IsNullOrEmpty(currentIDS))
{
idsArray = JArray.Parse(currentIDS);
}
else
{
idsArray = new JArray();
}
return new List<int>(idsArray.ToObject<int[]>());
}
/// <summary>
/// 跨页保持选中项 - 将表格当前页面选中行对应的数据同步到隐藏字段中
/// </summary>
/// <param name="hfSelectedIDS"></param>
/// <param name="grid"></param>
public void SyncSelectedRowIndexArrayToHiddenField(FineUI.HiddenField hfSelectedIDS, Grid grid)
{
List<int> ids = GetSelectedIDsFromHiddenField(hfSelectedIDS);
List<int> selectedRows = new List<int>();
if (grid.SelectedRowIndexArray != null && grid.SelectedRowIndexArray.Length > 0)
{
selectedRows = new List<int>(grid.SelectedRowIndexArray);
}
if (grid.IsDatabasePaging)
{
for (int i = 0, count = Math.Min(grid.PageSize, (grid.RecordCount - grid.PageIndex * grid.PageSize));
i < count;
i++)
{
int id = Convert.ToInt32(grid.DataKeys[i][0]);
if (selectedRows.Contains(i))
{
if (!ids.Contains(id))
{
ids.Add(id);
}
}
else
{
if (ids.Contains(id))
{
ids.Remove(id);
}
}
}
}
else
{
int startPageIndex = grid.PageIndex * grid.PageSize;
for (int i = startPageIndex, count = Math.Min(startPageIndex + grid.PageSize, grid.RecordCount);
i < count;
i++)
{
int id = Convert.ToInt32(grid.DataKeys[i][0]);
if (selectedRows.Contains(i - startPageIndex))
{
if (!ids.Contains(id))
{
ids.Add(id);
}
}
else
{
if (ids.Contains(id))
{
ids.Remove(id);
}
}
}
}
hfSelectedIDS.Text = new JArray(ids).ToString(Formatting.None);
}
/// <summary>
/// 跨页保持选中项 - 根据隐藏字段的数据更新表格当前页面的选中行
/// </summary>
/// <param name="hfSelectedIDS"></param>
/// <param name="grid"></param>
public void UpdateSelectedRowIndexArray(FineUI.HiddenField hfSelectedIDS, Grid grid)
{
List<int> ids = GetSelectedIDsFromHiddenField(hfSelectedIDS);
List<int> nextSelectedRowIndexArray = new List<int>();
if (grid.IsDatabasePaging)
{
for (int i = 0, count = Math.Min(grid.PageSize, (grid.RecordCount - grid.PageIndex * grid.PageSize));
i < count;
i++)
{
int id = Convert.ToInt32(grid.DataKeys[i][0]);
if (ids.Contains(id))
{
nextSelectedRowIndexArray.Add(i);
}
}
}
else
{
int nextStartPageIndex = grid.PageIndex * grid.PageSize;
for (int i = nextStartPageIndex, count = Math.Min(nextStartPageIndex + grid.PageSize, grid.RecordCount);
i < count;
i++)
{
int id = Convert.ToInt32(grid.DataKeys[i][0]);
if (ids.Contains(id))
{
nextSelectedRowIndexArray.Add(i - nextStartPageIndex);
}
}
}
grid.SelectedRowIndexArray = nextSelectedRowIndexArray.ToArray();
}
#endregion
#region 模拟树的下拉列表
protected List<T> ResolveDDL<T>(List<T> mys) where T : ICustomTree, ICloneable, IKeyID, new()
{
return ResolveDDL<T>(mys, -1, true);
}
protected List<T> ResolveDDL<T>(List<T> mys, int currentId) where T : ICustomTree, ICloneable, IKeyID, new()
{
return ResolveDDL<T>(mys, currentId, true);
}
// 将一个树型结构放在一个下列列表中可供选择
protected List<T> ResolveDDL<T>(List<T> source, int currentID, bool addRootNode)
where T : ICustomTree, ICloneable, IKeyID, new()
{
List<T> result = new List<T>();
if (addRootNode)
{
// 添加根节点
T root = new T();
root.Name = "--根节点--";
root.ID = -1;
root.TreeLevel = 0;
root.Enabled = true;
result.Add(root);
}
foreach (T item in source)
{
T newT = (T)item.Clone();
result.Add(newT);
// 所有节点的TreeLevel加一
if (addRootNode)
{
newT.TreeLevel++;
}
}
// currentId==-1表示当前节点不存在
if (currentID != -1)
{
// 本节点不可点击(也就是说当前节点不可能是当前节点的父节点)
// 并且本节点的所有子节点也不可点击,你想如果当前节点跑到子节点的子节点,那么这些子节点就从树上消失了
bool startChileNode = false;
int startTreeLevel = 0;
foreach (T my in result)
{
if (my.ID == currentID)
{
startTreeLevel = my.TreeLevel;
my.Enabled = false;
startChileNode = true;
}
else
{
if (startChileNode)
{
if (my.TreeLevel > startTreeLevel)
{
my.Enabled = false;
}
else
{
startChileNode = false;
}
}
}
}
}
return result;
}
#endregion
public static void UpLoadStreamToList<T>(FileUpload p_load)
{
}
#region 多语言功能
/// <summary>
/// 根据中文获得实际是那种语言
/// </summary>
/// <param name="p_key">传入中文</param>
/// <returns>返回实际语言翻译完成</returns>
protected string GetResourceKey(string p_key)
{
string _content = p_key;
if (!string.IsNullOrEmpty(p_key))
{
List<TA_LANGUAGE> _ls = null;
if (Application["LanguageList"] == null)
{
Application["LanguageList"] = ScpCache.LangauageList;
}
_ls = Application["LanguageList"] as List<TA_LANGUAGE>;
if (_ls != null)
{
var v_language = _ls.Where(p => p.CH == p_key).FirstOrDefault();
if (!string.IsNullOrEmpty(GetCurrentLanguage()) && v_language != null)
{
string _type = GetCurrentLanguage();
switch (_type)
{
case "CH":
_content = v_language.CH;
break;
case "FR":
_content = v_language.FR;
break;
case "DE":
_content = v_language.DE;
break;
case "EN":
_content = v_language.EN;
break;
case "JP":
_content = v_language.JP;
break;
default:
_content = v_language.CH;
break;
}
}
}
}
return _content;
}
/// <summary>
/// 当前语言
/// </summary>
/// <returns>当前选择语言</returns>
protected string GetCurrentLanguage()
{
if (Session["Language"] == null)
{
Session["Language"] = "CH";
}
return Session["Language"] as string;
}
/// <summary>
/// 转换控件
/// </summary>
/// <param name="p_grid">要翻译的Grid列</param>
protected void TranslatorAgent(params object[] p_crtls)
{
foreach (var p_crtl in p_crtls)
{
if (p_crtl is Grid)
{
Grid _grid = p_crtl as Grid;
foreach (var itm in _grid.Columns)
{
itm.HeaderText = GetResourceKey(itm.HeaderText);
}
}
if (p_crtl is Button)
{
Button _btn = p_crtl as Button;
_btn.Text = GetResourceKey(_btn.Text);
}
if (p_crtl is TextBox)
{
TextBox _tb = p_crtl as TextBox;
_tb.Label = GetResourceKey(_tb.Label);
}
if (p_crtl is TextArea)
{
TextArea _ta = p_crtl as TextArea;
_ta.Label = GetResourceKey(_ta.Label);
}
if (p_crtl is Label)
{
Label _label = p_crtl as Label;
_label.Label = GetResourceKey(_label.Label);
}
if (p_crtl is DropDownList)
{
DropDownList _dp = p_crtl as DropDownList;
_dp.Label = GetResourceKey(_dp.Text);
foreach (var itm in _dp.Items)
{
itm.Text = GetResourceKey(itm.Text);
}
}
if(p_crtl is RadioButtonList)
{
RadioButtonList _rb = p_crtl as RadioButtonList;
_rb.Label = GetResourceKey(_rb.Label);
foreach (var itm in _rb.Items)
{
itm.Text = GetResourceKey(itm.Text);
}
}
if (p_crtl is DatePicker)
{
DatePicker _date = p_crtl as DatePicker;
_date.Label = GetResourceKey(_date.Label);
}
if(p_crtl is CheckBoxList)
{
CheckBoxList _cbl= p_crtl as CheckBoxList;
_cbl.Label = GetResourceKey(_cbl.Label);
}
if (p_crtl is FineUI.Region)
{
FineUI.Region _region = p_crtl as FineUI.Region;
_region.Title = GetResourceKey(_region.Title);
}
if (p_crtl is Tab)
{
Tab _tab= p_crtl as Tab;
_tab.Title = GetResourceKey(_tab.Title);
}
}
}
protected void TranslatorAgents(params object[] p_crtls)
{
foreach (var p_crtl in p_crtls)
{
if (p_crtl is FormRow)
{
FormRow _formrow = p_crtl as FormRow;
foreach (var item in _formrow.Items)
{
TranslatorAgent(item);
}
}
if (p_crtl is Toolbar)
{
Toolbar _toolbar = p_crtl as Toolbar;
foreach (var item in _toolbar.Items)
{
TranslatorAgent(item);
}
}
if (p_crtl is Panel)
{
var _toolbar = p_crtl as Panel;
_toolbar.Title= GetResourceKey(_toolbar.Title);
foreach (var item in _toolbar.Items)
{
TranslatorAgent(item);
}
}
}
}
#endregion
public static string Upload(FileUpload fUpload, string ext)
{
string[] allowedExtensions = { ".jpg", ".gif", ".jpeg", ".png", ".rar", ".zip", ".flv", ".doc", ".docx", ".xls", ".xlsx", ".pdf", ".cad", ".txt" };//允许上传的文件类型
string filename = ""; //MyWebString.GetOrderNumber();
bool fileOK = false;
string fileExtension = System.IO.Path.GetExtension(fUpload.FileName).ToLower();
for (int i = 0; i < allowedExtensions.Length; i++)
{
if (fileExtension == allowedExtensions[i])
{
fileOK = true;
}
}
if (ext != "")
{
if (fileExtension != ext.ToLower())
{
throw new Exception("只能上传 " + ext + " 类型的文件!");
}
}
if (fileOK)
{
if (fUpload.HasFile)
{
// filename = GetMD5HashFromFile(fUpload.PostedFile.InputStream); //TODO 将文件名改为MD5
filename = System.Guid.NewGuid().ToString();
filename = filename + fileExtension;
// filename = Path.GetFileName(fUpload.FileName);
if (!File.Exists(System.Web.HttpContext.Current.Server.MapPath("~/uploadfiles/") + filename))
{
fUpload.SaveAs(System.Web.HttpContext.Current.Server.MapPath("~/uploadfiles/") + filename);
}
}
else
{
throw new Exception("文件上传失败!");
}
}
else
{
throw new Exception("上传文件格式不正确!");
}
return filename;
}
public static void ClosePostBack()
{
PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
}
public static void ClosePostBack(string arg)
{
PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference(arg));
}
public static void Close()
{
PageContext.RegisterStartupScript(ActiveWindow.GetHideReference());
}
public void WindowUpload_Close(object sender, WindowCloseEventArgs e)
{
try
{
string filename = e.CloseArgument.Trim();
if (filename != "")
{
filename = Server.MapPath("~/uploadfiles/" + filename);
Input(filename);
Alert.ShowInParent("数据导入成功!");
}
}
catch
{
}
}
/// <summary>
/// 导入数据
/// </summary>
/// <param name="filename"></param>
public virtual void Input(string filename)
{
try
{
DataSet dsInput = null;
// DbTransaction trans = null;
Code.MyExcelDatabase.OpenDatabase(filename, true);
dsInput = Code.MyOleDbDatabase.ExecuteDataSet("select * from [Sheet1$]");
Code.MyOleDbDatabase.CloseDatabase();
// trans = SCPDB.Database.Connection.BeginTransaction();
// TableManager.db.BeginTrans();
InputData(dsInput);
// TableManager.db.Commit();
// trans.Commit();
PageContext.Refresh();
}
catch (Exception ex)
{
// TableManager.db.Rollback();
throw new Exception("导入数据失败!\r\n" + ex.Message);
}
finally
{
// TableManager.db.EndTrans();
//Response.Redirect(Request.Url.ToString());
//Response.AddHeader("Refresh", "0");
//this.Refresh();
}
}
public virtual void InputData(DataSet dsInput)
{
}
#region 日志记录
protected void LogInfo(string message)
{
DB.Logs.Add(new Log
{
Level = "Info",
Message = message,
LogTime = DateTime.Now
});
DB.SaveChanges();
}
#endregion
public static string EntityListToExcel2003(Dictionary<string, string> cellHeard, IList enList, string sheetName,string title=null)
{
try
{
string fileName = sheetName + "-" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".xlsx"; // 文件名称
string urlPath = "/exportfiles/" + fileName; // 文件下载的URL地址,供给前台下载
string filePath = HttpContext.Current.Server.MapPath("\\" + urlPath); // 文件路径
// 1.检测是否存在文件夹,若不存在就建立个文件夹
string directoryName = Path.GetDirectoryName(filePath);
int _index = 0;
if (!Directory.Exists(directoryName))
{
Directory.CreateDirectory(directoryName);
}
XSSFWorkbook workbook = new XSSFWorkbook(); // 工作簿
ISheet sheet = workbook.CreateSheet(sheetName); // 工作表
List<string> keys = cellHeard.Keys.ToList();
if (title != null)
{
IRow row = sheet.CreateRow(0);
ICell cell = row.CreateCell(0);
ICellStyle style = workbook.CreateCellStyle();
style.Alignment = HorizontalAlignment.Center;
IFont font = workbook.CreateFont();
font.Boldweight = short.MaxValue;
font.FontHeight = 24;
style.SetFont(font);
cell.CellStyle = style;
cell.SetCellValue(title);
sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, keys.Count));
_index++;
}
// 2.解析单元格头部,设置单元头的中文名称
IRow row1 = sheet.CreateRow(_index);
for (int i = 0; i < keys.Count; i++)
{
row1.CreateCell(i).SetCellValue(cellHeard[keys[i]]); // 列名为Key的值
}
// 3.List对象的值赋值到Excel的单元格里
int rowIndex = _index+1; // 从第二行开始赋值(第一行已设置为单元头)
foreach (var en in enList)
{
IRow rowTmp = sheet.CreateRow(rowIndex);
for (int i = 0; i < keys.Count; i++) // 根据指定的属性名称,获取对象指定属性的值
{
string cellValue = ""; // 单元格的值
object properotyValue = null; // 属性的值
System.Reflection.PropertyInfo properotyInfo = null; // 属性的信息
// 3.1 若属性头的名称包含'.',就表示是子类里的属性,那么就要遍历子类,eg:UserEn.UserName
if (keys[i].IndexOf(".") >= 0)
{
// 3.1.1 解析子类属性(这里只解析1层子类,多层子类未处理)
string[] properotyArray = keys[i].Split(new string[] { "." }, StringSplitOptions.RemoveEmptyEntries);
string subClassName = properotyArray[0]; // '.'前面的为子类的名称
string subClassProperotyName = properotyArray[1]; // '.'后面的为子类的属性名称
System.Reflection.PropertyInfo subClassInfo = en.GetType().GetProperty(subClassName); // 获取子类的类型
if (subClassInfo != null)
{
// 3.1.2 获取子类的实例
var subClassEn = en.GetType().GetProperty(subClassName).GetValue(en, null);
// 3.1.3 根据属性名称获取子类里的属性类型
properotyInfo = subClassInfo.PropertyType.GetProperty(subClassProperotyName);
if (properotyInfo != null)
{
properotyValue = properotyInfo.GetValue(subClassEn, null); // 获取子类属性的值
}
}
}
else
{
// 3.2 若不是子类的属性,直接根据属性名称获取对象对应的属性
properotyInfo = en.GetType().GetProperty(keys[i]);
if (properotyInfo != null)
{
properotyValue = properotyInfo.GetValue(en, null);
}
}
// 3.3 属性值经过转换赋值给单元格值
if (properotyValue != null)
{
if (enList.GetType() != null && enList.GetType().FullName != null && enList.GetType().FullName.Contains("V_TB_RECEIVE"))
{
cellValue = properotyValue.ToString();
if ("State" == keys[i])
{
if ("0" == properotyValue.ToString())
{
cellValue = "已收货";
}
else if ("1" == properotyValue.ToString())
{
cellValue = "审核通过";
}
else if ("2" == properotyValue.ToString())
{
cellValue = "已开票";
}
}
}
else if (enList.GetType() != null && enList.GetType().FullName != null && enList.GetType().FullName.Contains("V_TB_REJECT"))
{
cellValue = properotyValue.ToString();
if ("State" == keys[i])
{
if ("0" == properotyValue.ToString())
{
cellValue = "已退货";
}
else if ("1" == properotyValue.ToString())
{
cellValue = "审核通过";
}
}
}
else
{
cellValue = properotyValue.ToString();
}
// 3.3.1 对时间初始值赋值为空
if (cellValue.Trim() == "0001/1/1 0:00:00" || cellValue.Trim() == "0001/1/1 23:59:59")
{
cellValue = "";
}
}
// 3.4 填充到Excel的单元格里
if (properotyInfo.PropertyType.FullName == "System.Decimal")
{
rowTmp.CreateCell(i, CellType.Numeric).SetCellValue(Convert.ToDouble(cellValue));
}
else
{
rowTmp.CreateCell(i, CellType.String).SetCellValue(cellValue);
}
if (properotyInfo.Name.Contains("日期")||properotyInfo.Name.Contains("时间"))
{
ICellStyle style = workbook.CreateCellStyle();
IDataFormat dataFormatCustom = workbook.CreateDataFormat();
style.DataFormat = dataFormatCustom.GetFormat("@");
rowTmp.Cells[i].CellStyle = style;
}
}
rowIndex++;
}
// 4.生成文件
FileStream file = new FileStream(filePath, FileMode.Create);
workbook.Write(file);
file.Close();
Alert.Show($"<a href=\'/exportfiles/{fileName}\'>{fileName}</a>", "文件导出成功,请点击文件名下载", MessageBoxIcon.Information);
// 5.返回下载路径
return urlPath;
}
catch (Exception ex)
{
throw ex;
}
}
public static void DataSetToExcel(DataSet p_dataset, string sheetName,string title = null)
{
try
{
EpPlusHelper _helper = new EpPlusHelper();
_helper.ExportExcelCompleted += (filePath,fileName) => {
Alert.Show($"<a href=\'/exportfiles/{fileName}\'>{fileName}</a>", "文件导出成功,请点击文件名下载", MessageBoxIcon.Information);
};
_helper.WriteDsToExcel(sheetName, p_dataset, title);
}
catch (Exception ex)
{
throw ex;
}
}
protected void DisplayColumn(Grid p_grid,bool p_visible, params string[] p_header)
{
foreach (var itm in p_grid.Columns)
{
if (p_header.Contains(itm.HeaderText))
{
itm.Hidden = p_visible;
}
}
}
#region 将list转换为datatable
public static DataTable ToDataTable<T>(List<T> items)
{
var tb = new DataTable(typeof(T).Name);
PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo prop in props)
{
Type t = GetCoreType(prop.PropertyType);
tb.Columns.Add(prop.Name, t);
}
foreach (T item in items)
{
var values = new object[props.Length];
for (int i = 0; i < props.Length; i++)
{
values[i] = props[i].GetValue(item, null);
}
tb.Rows.Add(values);
}
return tb;
}
public static bool IsNullable(Type t)
{
return !t.IsValueType || (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>));
}
public static Type GetCoreType(Type t)
{
if (t != null && IsNullable(t))
{
if (!t.IsValueType)
{
return t;
}
else
{
return Nullable.GetUnderlyingType(t);
}
}
else
{
return t;
}
}
public string GetHtmlString(DataTable dt)
{
StringBuilder sb = new StringBuilder();
sb.Append("<html><head>");
sb.Append("<title>Excel转换为Table</title>");
sb.Append("<meta http-equiv='content-type' content='text/html; charset=GB2312'> ");
sb.Append("<style type=text/css>");
sb.Append("td{font-size: 9pt;border:solid 1 #000000;}");
sb.Append("table{padding:3 0 3 0;border:solid 1 #000000;margin:0 0 0 0;BORDER-COLLAPSE: collapse;}");
sb.Append("</style>");
sb.Append("</head>");
sb.Append("<body>");
sb.Append("<table cellSpacing='0' cellPadding='0' width ='100%' border='1'>");
sb.Append("<tr valign='middle'>");
sb.Append("<td><b></b></td>");
foreach (DataColumn column in dt.Columns)
{
sb.Append("<td><b><span>" + column.ColumnName + "</span></b></td>");
}
sb.Append("</tr>");
int iColsCount = dt.Columns.Count;
int rowsCount = dt.Rows.Count - 1;
for (int j = 0; j <= rowsCount; j++)
{
sb.Append("<tr>");
sb.Append("<td>" + ((int)(j + 1)).ToString() + "</td>");
for (int k = 0; k <= iColsCount - 1; k++)
{
sb.Append("<td>");
object obj = dt.Rows[j][k];
if (obj == DBNull.Value)
{
obj = "&nbsp;";//如果是NULL则在HTML里面使用一个空格替换之
}
if (obj.ToString() == "")
{
obj = "&nbsp;";
}
string strCellContent = obj.ToString().Trim();
sb.Append("<span>" + strCellContent + "</span>");
sb.Append("</td>");
}
sb.Append("</tr>");
}
sb.Append("</table>");
sb.Append("<script src='https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js'></script>");
sb.Append("<script type='text/javascript'>");
sb.Append("$('table tbody').on('click', 'td', function (e) {");
sb.Append("var row = $(this).parent().prevAll().length-1 ;");
sb.Append("var column = $(this).prevAll().length-1 ;");
sb.Append("var str = 'dt.Rows[' + row + '][' + column + '].ToString()';");
sb.Append("console.log(str);alert(str);");
sb.Append("});");
sb.Append("</script>");
sb.Append("</body></html>");
return sb.ToString();
}
#endregion
}
}