----判断日期合理性-----
if
(
!
DateTime.TryParse(Request.Form[
"
beginTime
"
],
out
beginDate)
||
!
DateTime.TryParse(Request.Form[
"
endTime
"
],
out
endDate)) {
Response.Write(JsonHelper.GetMessage( false , " 参数非法 " ));
Response.End();
return ;
}
Response.Write(JsonHelper.GetMessage( false , " 参数非法 " ));
Response.End();
return ;
}
--------
if
(act.Equals(
"
GetList
"
)) {}
-------------
int pageIndex;
int.TryParse(Request.Form["pageIndex"], out pageIndex);
-----
Newtonsoft.Json 实现DataTable转Json格式数据
1 .这里下载:http: // www.newtonsoft.com/products/json/
安装:
1 .解压下载文件,得到Newtonsoft.Json.dll
2 .在项目中添加引用
2 .引入命名空间
3 .把datatable转换成json格式
1 . public string GetAllCategory()
2 .{
3 . string result = "" ;
4 . DataTable dt = catDAO.GetAllCategory();
5 . result = JsonConvert.SerializeObject(dt, new DataTableConverter());
6 . return result;
7 . }
1 .这里下载:http: // www.newtonsoft.com/products/json/
安装:
1 .解压下载文件,得到Newtonsoft.Json.dll
2 .在项目中添加引用
2 .引入命名空间
3 .把datatable转换成json格式
1 . public string GetAllCategory()
2 .{
3 . string result = "" ;
4 . DataTable dt = catDAO.GetAllCategory();
5 . result = JsonConvert.SerializeObject(dt, new DataTableConverter());
6 . return result;
7 . }
---------
try
{ }
catch
(Exception ex) {
LogHelper.WriteLog(GetType(), LogStatusLevel.ERROR, ex.Message);
isError = false ;
}
if ( ! isError) {
Response.Write(JsonHelper.GetMessage( false , " 参数错误 " ));
} else {
Response.Write(JsonHelper.GetMessage( true , " 优先级干预成功 " ));
}
LogHelper.WriteLog(GetType(), LogStatusLevel.ERROR, ex.Message);
isError = false ;
}
if ( ! isError) {
Response.Write(JsonHelper.GetMessage( false , " 参数错误 " ));
} else {
Response.Write(JsonHelper.GetMessage( true , " 优先级干预成功 " ));
}
-------
function bindSubmit() {
$('#btn_submit').bind('click', function () {
var p = Array();
p['ad_type'] = $('#ad_type').val();
p['ad_name'] = $.trim($('#ad_name').val());
p['ad_intro'] = $.trim($('#ad_intro').val());
p['type'] = $('#type').val(); //品牌广告
if (p['ad_name'] == '') {
myError('广告名称不能为空!');
return;
} else if (strlen(p['ad_name']) < 6) {
myError('广告名称太短,长度6-30个字符包含汉字、字母、数字和\'-\'线!');
return;
} else if (strlen(p['ad_name']) > 30) {
myError('广告名称太长,长度6-30个字符包含汉字、字母、数字和\'-\'线!');
return;
} else if (p['ad_name'].IsWrongCharacter()) {
myError('广告名称不能出现 {}:;,[]!@#$%^&*()+=<>/\"\'.? 这样的字符!');
return;
}
if (strlen(p['ad_intro']) > 300) {
myError('广告简介太长,请您控制在300个字符(150)个汉字以内!');
$('#ad_intro').focus();
return;
}
提交表单
var post = '';
for (var item in p) {
post += item + '=' + encodeURIComponent(p[item]) + '&';
}
$.ajax({
type: 'post',
async: false,
url: './MyAd.aspx?act=AddAdAction&r=' + r(),
data: post,
error: function (r) { StatusAlert(r.status); },
success: function (data) {
if (data.result == 'false') {
myError(data.msg);
} else {
if (data.msg.CanSubmit) {
myConfirm("已经添加成功,您是否需要提交审核?", function confirmAction() {
$.ajax({
type: 'post',
async: false,
url: './MyAd.aspx?act=SubmitToCheck&r=' + r(),
data: { 'ad_id': data.msg.AdId },
error: function (r) { StatusAlert(r.status); },
success: function (data) {
if (data.result == 'true') {
mySucceedWhitAutoClose(data.msg);
GetWorkareaHtml('AdManager.aspx');
} else {
myError(data.msg);
}
}
});
}, function cancelAction() {
myAlert("广告审核已取消,您可以进入管理广告,对未提交审核的广告进行修改,然后重新提交。");
GetWorkareaHtml('AdManager.aspx');
});
});
}
------Tolist()
<!--授权的上传文件后缀名--> <add key="validFileTypes" value="gif,jpg,png,3gp,mp4"/>
validUpLoadFileType = new List<string>();
string fileTypes = ConfigurationManager.AppSettings["validFileTypes"];
if (!string.IsNullOrEmpty(fileTypes)) {
validUpLoadFileType = fileTypes.Split(',').ToList();
------webutil.cs
/// <summary>
/// 获取Request.QueryString的值
/// </summary>
/// <typeparam name="T">获取值后要转换的类型</typeparam>
/// <param name="key">参数名称</param>
/// <param name="value">默认值(如果转换失败或者没有此参数,则使用此值)</param>
/// <returns></returns>
public static T GetQueryValue<T>(string key, T value = default(T))
{
var queryStr = HttpContext.Current.Request.QueryString[key];
if (queryStr.IsNullOrEmpty())
return value;
try
{
return queryStr.ConvertTo<T>(); ;
}
catch
{
return value;
}
}
/// <summary>
/// 获取Request.Form的值
/// </summary>
/// <typeparam name="T">获取值后要转换的类型</typeparam>
/// <param name="key">参数名称</param>
/// <param name="value">默认值(如果转换失败或者没有此参数,则使用此值)</param>
/// <returns></returns>
public static T GetFormValue<T>(string key, T value = default(T))
{
var formValue = HttpContext.Current.Request.Form[key];
if (formValue.IsNullOrEmpty())
return value;
try
{
return formValue.ConvertTo<T>();
}
catch
{
return value;
}
}
/// <summary>
/// 获取Request.QueryString或者Request.Form的值
/// </summary>
/// <typeparam name="T">获取值后要转换的类型</typeparam>
/// <param name="key">参数名称</param>
/// <param name="value">默认值(如果转换失败或者没有此参数,则使用此值)</param>
/// <returns></returns>
public static T GetParamsValue<T>(string key, T value = default(T))
{
var formValue = HttpContext.Current.Request.Params[key];
if (formValue.IsNullOrEmpty())
return value;
try
{
return formValue.ConvertTo<T>(); ;
}
catch
{
return value;
}
}
public static string BuildUrlParameterString(IList<KeyValuePair<string, object>> dic)
{
if (dic.Count == 0)
{
return string.Empty;
}
var sb = new StringBuilder();
foreach (var kvp in dic)
{
if (sb.Length > 0)
sb.Append("&");
sb.Append("{0}={1}".FormatString(kvp.Key, kvp.Value.ToString().UrlEncode()));
}
return sb.ToString();
}
/// <summary>
/// 判断字符串是否为空
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static bool IsNullOrEmpty(this string value)
{
return String.IsNullOrEmpty(value);
}
/// <summary>
/// 格式化字符串
/// 例如 "{0}{1}".FormatString("百分","通联")
/// </summary>
/// <param name="value"></param>
/// <param name="args"></param>
/// <returns></returns>
public static string FormatString(this string value, params object[] args)
{
return string.Format(value, args);
}
/// <summary>
/// 判断字符串是否匹配正则表达式
/// </summary>
/// <param name="value"></param>
/// <param name="pattern"></param>
/// <returns></returns>
public static bool IsMatch(this string value, string pattern)
{
if (value.IsNullOrEmpty()) return false;
return Regex.IsMatch(value, pattern);
}
/// <summary>
/// 取出字符串中符合正则表达式的字符串
/// </summary>
/// <param name="value"></param>
/// <param name="pattern"></param>
/// <returns></returns>
public static string Match(this string value, string pattern)
{
if (value.IsNullOrEmpty()) return string.Empty;
return Regex.Match(value, pattern).Value;
}
/// <summary>
/// 获取字符串长度,中文英文都算一个字符
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static int GetStringLength(this string value)
{
return value.Length;
}
/// <summary>
/// 获取字符串长度,中文算2个字符
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static int GetStringTrueLength(this string value)
{
if (value.IsNullOrEmpty()) return 0;
return Encoding.Default.GetBytes(value).Length;
}
/// <summary>
/// 截取字符串指定长度,如果超过指定长度,则用fillString代替
/// </summary>
/// <param name="value"></param>
/// <param name="count"></param>
/// <param name="fillString"></param>
/// <returns></returns>
public static string FixWidth(this string value, int count, string fillString = "...")
{
var len = value.GetStringLength();
if (len <= count) return value;
return string.Concat(value.Substring(0, count), fillString);
}
/// <summary>
/// 对字符串进行Html编码
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static string HtmlEncode(this string value)
{
return HttpUtility.HtmlEncode(value);
}
/// <summary>
/// 对字符串进行Html解码
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static string HtmlDecode(this string value)
{
return HttpUtility.HtmlDecode(value);
}
/// <summary>
/// 对字符串进行Url编码
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static string UrlEncode(this string value, Encoding encoding = null)
{
if(encoding == null)
encoding = Encoding.UTF8;
return HttpUtility.UrlEncode(value, encoding);
}
/// <summary>
/// 对字符串进行Url解码
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static string UrlDecode(this string value, Encoding encoding)
{
if (encoding == null)
encoding = Encoding.UTF8;
return HttpUtility.UrlDecode(value, encoding);
}
/// <summary>
/// 使用MD5加密字符串
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static string MD5String(this string value)
{
if (value.IsNullOrEmpty()) return string.Empty;
return FormsAuthentication.HashPasswordForStoringInConfigFile(value, "MD5");
}
/// <summary>
/// 把字符串进行Base64编码
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static string Base64Encode(this string value)
{
if (value.IsNullOrEmpty()) return string.Empty;
var bytes = value.StringToBytes();
return BytesToBase64String(bytes);
}
/// <summary>
/// 字符串转换成字节
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static byte[] StringToBytes(this string value)
{
return Encoding.UTF8.GetBytes(value);
}
/// <summary>
/// 字节转换成字符串
/// </summary>
/// <param name="bytes"></param>
/// <returns></returns>
public static string BytesToString(byte[] bytes)
{
return Encoding.UTF8.GetString(bytes);
}
/// <summary>
/// 解码Base64字符串
/// </summary>
/// <param name="base64String"></param>
/// <returns></returns>
public static string DecodeBase64String(string base64String)
{
var bytes = Base64StringToBytes(base64String);
return BytesToString(bytes);
}
/// <summary>
/// 字节转换成Base64字符串
/// </summary>
/// <param name="bytes"></param>
/// <returns></returns>
public static string BytesToBase64String(byte[] bytes)
{
return System.Convert.ToBase64String(bytes);
}
/// <summary>
/// 将Base64字符转换成字节
/// </summary>
/// <param name="base64String"></param>
/// <returns></returns>
public static byte[] Base64StringToBytes(string base64String)
{
return System.Convert.FromBase64String(base64String);
}
/// <summary>
/// 流转换成字节
/// </summary>
/// <param name="stream"></param>
/// <returns></returns>
public static byte[] StreamToByte(Stream stream)
{
var bytes = new byte[stream.Length];
stream.Read(bytes, 0, bytes.Length);
stream.Seek(0, SeekOrigin.Begin);
return bytes;
}
/// <summary>
/// 字节转换成流
/// </summary>
/// <param name="bytes"></param>
/// <returns></returns>
public static Stream BytesToStream(byte[] bytes)
{
var stream = new MemoryStream(bytes);
return stream;
}
/// <summary>
/// 将流写入文件
/// </summary>
/// <param name="stream"></param>
/// <param name="fileName"></param>
public static void StreamToFile(Stream stream, string fileName)
{
var bytes = new byte[stream.Length];
stream.Read(bytes, 0, bytes.Length);
// 设置当前流的位置为流的开始
stream.Seek(0, SeekOrigin.Begin);
// 把 byte[] 写入文件
var fs = new FileStream(fileName, FileMode.Create);
var bw = new BinaryWriter(fs);
bw.Write(bytes);
bw.Close();
fs.Close();
}
/// <summary>
/// 把文件转换成流
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
public static Stream FileToStream(string fileName)
{
// 打开文件
var fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
// 读取文件的 byte[]
var bytes = new byte[fileStream.Length];
fileStream.Read(bytes, 0, bytes.Length);
fileStream.Close();
// 把 byte[] 转换成 Stream
Stream stream = new MemoryStream(bytes);
return stream;
}
/// <summary>
/// 获取虚拟目录的绝对路径 去最后"/"
/// </summary>
/// <returns></returns>
public static string GetVirtualPathUrl()
{
string mlgPath = "http://" + HttpContext.Current.Request.Url.Host + ":" + HttpContext.Current.Request.Url.Port + HttpContext.Current.Request.ApplicationPath;
if (mlgPath.LastIndexOf('/') == mlgPath.Length - 1)
{
mlgPath = mlgPath.Substring(0, mlgPath.LastIndexOf('/'));
}
return mlgPath;
}
public static bool IsNullableType(this System.Type type)
{
return type != null && type.IsGenericType && type.GetGenericTypeDefinition() == typeof(System.Nullable<>);
}
/// <summary>
/// Object对象转换成泛型对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value"></param>
/// <param name="format"></param>
/// <returns></returns>
public static T ConvertTo<T>(this object value, string format = null)
{
var typeFromHandle = typeof(T);
var obj = value.ConvertTo(typeFromHandle, format);
if (obj == null && typeFromHandle.IsValueType && !typeFromHandle.IsNullableType())
{
throw new System.Exception("值类型不能返回null。");
}
return (T)obj;
}
/// <summary>
/// Object对象转换成泛型对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value"></param>
/// <param name="format"></param>
/// <returns></returns>
public static object ConvertTo(this object value, System.Type type, string format = null)
{
if (value == null || type.IsInstanceOfType(value))
{
return value;
}
var flag = type.IsNullableType();
if (flag && value.ToString().IsNullOrEmpty())
{
return null;
}
var type2 = flag ? System.Nullable.GetUnderlyingType(type) : type;
string key;
if ((key = type2.ToString()) != null)
{
if (TypeDic == null)
{
var dic = new System.Collections.Generic.Dictionary<string, int>(15);
dic.Add("System.Byte", 0);
dic.Add("System.SByte", 1);
dic.Add("System.Int16", 2);
dic.Add("System.Int32", 3);
dic.Add("System.Int64", 4);
dic.Add("System.UInt16", 5);
dic.Add("System.UInt32", 6);
dic.Add("System.UInt64", 7);
dic.Add("System.Single", 8);
dic.Add("System.Double", 9);
dic.Add("System.Decimal", 10);
dic.Add("System.Boolean", 11);
dic.Add("System.Char", 12);
dic.Add("System.String", 13);
dic.Add("System.DateTime", 14);
TypeDic = dic;
}
int num;
if (TypeDic.TryGetValue(key, out num))
{
object result;
switch (num)
{
case 0:
{
result = System.Convert.ToByte(value);
break;
}
case 1:
{
result = System.Convert.ToSByte(value);
break;
}
case 2:
{
result = System.Convert.ToInt16(value);
break;
}
case 3:
{
result = System.Convert.ToInt32(value);
break;
}
case 4:
{
result = System.Convert.ToInt64(value);
break;
}
case 5:
{
result = System.Convert.ToUInt16(value);
break;
}
case 6:
{
result = System.Convert.ToUInt32(value);
break;
}
case 7:
{
result = System.Convert.ToUInt64(value);
break;
}
case 8:
{
result = System.Convert.ToSingle(value);
break;
}
case 9:
{
result = System.Convert.ToDouble(value);
break;
}
case 10:
{
result = System.Convert.ToDecimal(value);
break;
}
case 11:
{
if (typeof(string).IsInstanceOfType(value))
{
var s = value.ToString().Trim().ToUpper();
if (s == "TRUE")
{
result = true;
}
else
{
if (s == "FALSE")
{
result = false;
}
else
{
result = System.Convert.ToBoolean(int.Parse(s));
}
}
}
else
{
result = System.Convert.ToBoolean(value);
}
break;
}
case 12:
{
result = System.Convert.ToChar(value);
break;
}
case 13:
{
result = System.Convert.ToString(value);
break;
}
case 14:
{
if (!string.IsNullOrEmpty(format))
{
result = System.DateTime.ParseExact(value.ToString(), format, null);
}
else
{
result = System.Convert.ToDateTime(value);
}
break;
}
default:
{
goto error;
}
}
return result;
}
}
error:
throw new System.ArgumentException("不支持此类型的转换。", "convertionType");
}
/// <summary>
/// 判断Object对象是否为Null 或 DBNull
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static bool IsNullOrDBNull(this object value)
{
return value == null || value == DBNull.Value;
}