1、C# Split分割字符串的方法使用
if (!string.IsNullOrEmpty(query.SchoolTime))
{
var arr = string.Join(",", query.SchoolTime.Split(new char[]{'-'}, StringSplitOptions.RemoveEmptyEntries).Select(c=>string.Format("'{0}'",c.Trim())));
searchSql += string.Format(" and c.Grade in({0})",arr);
}
var tasknotifiIds = string.Join(",", result.Data.Select(v => string.Format("'{0}'", v.Id)));
2、jQuery序列化表单数据
serialize()、serializeArray()方法都是jQuery用户序列化表单的,用于ajax提交的data值的序列化
var dataParam = $("#updateChannelForm").serializeArray();
例如我想添加sex="男"
dataParam.push({"name":"sex","value":"男"}) 就可以了
我们看到serialize()方法把表单里的内容序列化成了字符串
"id=58&channelType=2&subTitle=591teststetets&extAttrValueId=599"
那么我们只需这要添加额外的内容:
var dataParam = $("#updateChannelForm").serialize();
例如我想添加sex="男"
dataParam =dataParam +"&"+"sex=男"
参考出处:http://blog.csdn.net/csdnzhangtao5/article/details/52981541
var formData = $form.serialize();
formData += '[email protected][email protected]';
formData = formData.replace(/\+/g, " "); //jquery的serialize将空格变成了+,替换回来
3、jQuery closest() 方法获得匹配选择器的第一个祖先元素,从当前元素开始沿 DOM 树向上。
$(document).bind("click", function( e ) {
$( e.target ).closest("li").toggleClass("hilight");
});
4、Dynamic动态参数
dynamic param = new ExpandoObject();
param.StudentId = studentId;
if (!string.IsNullOrEmpty(courseId))
{
sql += " and b.CourseId=@CourseId";
param.CourseId = courseId;
}
var model = await _baseService.GetList(sql, param);
return model;
5、处理input type="number"输入e的问题,及maxlength不起作用
分
function handleScore(obj, len) { //处理数字输入
//if (obj.value) {obj.value = obj.value.replace(/[^0-9]/, ""); }
if (obj.value.length > len) { obj.value = obj.value.slice(0, len); }
if (obj.value < 0) { obj.value = 0; }
}
6、基于声明的登录和退出
http://www.cnblogs.com/dudu/p/6367303.html
var identity = new ClaimsIdentity(DefaultAuthenticationTypes.ApplicationCookie);
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id));
identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));
identity.AddClaim(new Claim(ClaimTypes.Sid, school.Id));
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = model.RememberMe }, identity);
//退出
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
return RedirectToAction("Login", "Account");
/*
IList claimCollection = new List
{
new Claim(ClaimTypes.Name, "Andras")
, new Claim(ClaimTypes.Country, "Sweden")
, new Claim(ClaimTypes.Gender, "M")
, new Claim(ClaimTypes.Surname, "Nemes")
, new Claim(ClaimTypes.Email, "[email protected]")
, new Claim(ClaimTypes.Role, "IT")
};
ClaimsIdentity claimsIdentity = new ClaimsIdentity(claimCollection, "My e-commerce website");
//Console.WriteLine(claimsIdentity.IsAuthenticated);
ClaimsPrincipal principal = new ClaimsPrincipal(claimsIdentity);
Thread.CurrentPrincipal = principal;
//actionContext.RequestContext.Principal = principal;
*/
7、基于Forms身份验证的关键代码:
Web.Config配置
///
/// 验证后台用户名和密码
///
///
///
///
[AllowAnonymous]
public ActionResult LoginValidate(string UserName, string UserPwd)
{
BackResult backResult;
string md5Pwd = UserPwd.MD5(); //MD5加密后的密码
MS.Model.SysUser user = new SysUser_BLL().LoginValidate(UserName, md5Pwd);
if (user != null)
{
//为提供的用户名提供一个身份验证的票据
FormsAuthentication.SetAuthCookie(UserName, true, FormsAuthentication.FormsCookiePath);
//把用户对象保存在票据里
string userData = JsonConvert.SerializeObject(user);
FormsAuthenticationTicket Ticket = new FormsAuthenticationTicket(1, UserName, DateTime.Now, DateTime.Now.AddTicks(FormsAuthentication.Timeout.Ticks), false, userData);
//加密票据
string hashTicket = FormsAuthentication.Encrypt(Ticket);
HttpCookie userCookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashTicket);
Response.Cookies.Add(userCookie);
//登录成功之后,改写用户的最后一次登录时间及增加登录次数
new SysUser_BLL().ModifyLoginInfo(user);
string loginIP = Util.ClientIP;
LogHelper.WriteOpLog(new SysLog { OpTit = "登录", Operator = UserName, OpPage = "登录页面", OpTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), OpType = OpType.登录, OpIP= loginIP });
backResult = new BackResult { status = 100, msg = "通过身份验证!" };
}
else
{
backResult = new BackResult { status = 200, msg = "用户名或密码不正确!" };
}
return Json(backResult, JsonRequestBehavior.AllowGet);
}
[AllowAnonymous]
public void LogOut() //退出登录
{
FormsAuthentication.SignOut();
}
BaseController
[Authorize]
public class BaseController : Controller
{
public string LoginUser
{
get
{
HttpCookie authCookie = HttpContext.Request.Cookies[FormsAuthentication.FormsCookieName];//获取cookie
if (authCookie != null)
{
FormsAuthenticationTicket Ticket = FormsAuthentication.Decrypt(authCookie.Value);//解密
MS.Model.SysUser loginUser = JsonConvert.DeserializeObject(Ticket.UserData);//反序列化
return loginUser;
}
else
{
return null;
}
}
}
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
//获取区域
var area = filterContext.RouteData.DataTokens;//MVC可以有区域的,这里就是负责存放区域的
//获取区域名称
var areaName = area["area"];//这个["area"]是写死了的。你根据["area"]就可以取到区域名称,因为区域的key固定就是area
string controllerName = (string)filterContext.RouteData.Values["controller"]; //控制器名称
string actionName = (string)filterContext.RouteData.Values["action"]; //Action方法名称
//TODO:根据用户所属的角色,用户权限判断用户是否具有访问这个 区域下controller的action方法
}
}
8、Html拼接时正则替换,免得每次手敲
(.+) -> html+='$0';
9、WebForm中的文件下载
string fileName = lb_file.Text;//客户端保存的文件名
string filePath = Server.MapPath("~/Report/" + fileName);//路径
if (!File.Exists(filePath))
{
MessageBox.Show(this, "文件已经删除!无法下载!"); return;
}
//以字符流的形式下载文件
var fs = new FileStream(filePath, FileMode.Open);
var bytes = new byte[(int)fs.Length];
fs.Read(bytes, 0, bytes.Length);
fs.Close();
Response.ContentType = "application/octet-stream";
//通知浏览器下载文件而不是打开
Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, Encoding.UTF8));
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
MVC文件下载:http://www.cnblogs.com/insus/p/3615714.html
10、阻止浏览器按F5刷新页面
$(document).keydown(function (e) {
if (e.keyCode === 116) {
layer.confirm('如果您正在上传资料请不要刷新当前页', {
btn: ['确定刷新', '取消'] //按钮
}, function () {
window.location.reload();
});
return false;
}
});
//原生js写法
document.onkeydown = function (e) {
var ev = window.event || e;
var code = ev.keyCode || ev.which;
if (code == 116) {
return false;
}
}
11、select下拉框设置了multiple时,变成了多行展示,撑高了原有的展示区域
解决方式,再加上 size="1"
12、zTree树
function loadTreeData(url, key, selectNodeId) {
$.post(url, { key: key }, function (data) {
if (data && data.Tree) {
$("span[name='SchoolIndicator']").text(data.SchoolIndicator);
$("span[name='MajorIndicator']").text(data.MajorIndicator);
bindTree(data.Tree, selectNodeId);
}
});
}
function bindTree(data, selectNodeId) {
var zTree = $.fn.zTree.init($("#treeDemo"), setting, data);
if (data.length > 0) {
var nodes = zTree.getNodes();
var node = getChildren(nodes[0]);
if (selectNodeId) {
node = zTree.getNodeByParam('Id', selectNodeId);
}
if (node) {
if ($.trim($("#indicatorKey").val()) === "") {
zTree.expandNode(node);
} else {
zTree.expandAll(true);
}
zTree.selectNode(node);
treeNodeSelected(node);
}
setTimeout("$('.scroll-pane').jScrollPane()", 150);
} else {
resetStyle();
}
}
///获取第一个叶子节点
function getChildren(treeNode) {
var childrenNodes = treeNode.children;
if (childrenNodes) {
return getChildren(treeNode.children[0]);
} else {
return treeNode;
}
}
function treeNodeSelected(node) {
selectedNode = node;
setButtonStyle(node);
if (node.isParent) {
loadCatalogData(node);
} else {
loadContentData(node);
}
}
function getPath(node) {
var paths = [];
while (node != null) {
paths.push(node.IndicatorName);
node = node.getParentNode();
}
var strPath = paths.reverse().join(">>");
//if (strPath.length > 70) {
// strPath = strPath.substr(0, 70) + '...';
//}
return strPath;
}
用while过滤掉没有叶子节点的父级
public async Task> GetMajorTreeNew(string key,bool parentNodeNoCheck = true)
{
var orgList = (await _organizationService.GetAllOrgnization()).ToList();
var majorList = (await _majorService.GetAllList()).ToList();
if (orgList.Count > 0 && majorList.Count > 0)
{
Dictionary hasChildrenDic=new Dictionary(); //有叶子节点的父级
var distinctParents = majorList.Where(c=>c.OrganizationId.Trim().Length>0).Select(c => c.OrganizationId).Distinct().ToList();
for (int i = 0; i < distinctParents.Count(); i++)
{
var node = orgList.FirstOrDefault(c => c.Id == distinctParents[i]);
if (node == null) continue;
hasChildrenDic.Add(distinctParents[i],node);
Organization tempOrg = orgList.FirstOrDefault(c=>c.Id==node.ParentId);
if (tempOrg != null)
{
while (tempOrg != null && tempOrg.Id.Length>1)
{
if (!hasChildrenDic.ContainsKey(tempOrg.Id))
{
hasChildrenDic.Add(tempOrg.Id, tempOrg);
tempOrg = orgList.FirstOrDefault(c => c.Id == tempOrg.ParentId);
}
else
{
tempOrg = null;
}
}
}
}
var itreeList = hasChildrenDic.Select(ic => new SelectTreeModel
{
Id = ic.Value.Id,
Pid = ic.Value.ParentId,
name = ic.Value.OrgName,
isParent = true,
nocheck = parentNodeNoCheck,
Open = true,
Sort = ic.Value.Sort
}).ToList();
itreeList.AddRange(from v in majorList
where orgList.FirstOrDefault(d => d.Id == v.OrganizationId) != null
select new SelectTreeModel()
{
Id = v.Id,
Pid = v.OrganizationId,
name = v.MajorName,
nocheck = false,
isParent = false,
Open = true,
Sort = 10000
});
var result = GetSelectTree(itreeList, key);
return result.OrderBy(d => d.Sort).ToList();
}
return null;
}
13、C#扩展方法 GroupBy
//先对老师学期内的月数据分组求和
var grouped = details.GroupBy(o => new { o.OrgName, o.EmployeeId }).Select(g => new
{
g.Key.OrgName,
totalHour = g.Sum(c => c.ConfirmClassHour)
}).GroupBy(c => c.OrgName).ToDictionary(o => o.Key, o => o.Count(c => c.totalHour < 150));
query.GroupBy(q => new { q.Year, q.Month })
.Select(q => new
{
Year = q.Key.Year,
Month = q.Key.Month,
BuildAmount = q.Sum(i => i.BuildAmount),
RecAmount = q.Sum(i => i.RecAmount),
Amount = q.Sum(i => i.Amount),
RealAmount = q.Sum(i => i.RealAmount)
});
//Linq方式
var query = from l in list
group l by new { l.Name, l.BatNum } into g
select new
{
Name = g.Key.Name,
Count = g.Sum(a => a.Count),
BatNum = g.Key.BatNum
};
Dictionary buildList = _build.FindList().GroupBy(q => q.SaleCode)
.Select(q => new { Code = q.Key, ReaAmount = q.Sum(i => i.RealAmount) })
.ToDictionary(q => q.Code, q => q.ReaAmount);
14、JsonConvert格式化日期格式
var tables = details.OrderByDescending(o => o.AccidentTime).ToList();
return JsonConvert.SerializeObject(tables,new IsoDateTimeConverter(){DateTimeFormat = "yyyy-MM-dd"});