C#、NET、JS常用方法记录

1、js前端页面获取后台返回的list集合

var topupList = ViewBag.TopupList;

function TopupPage(pageIndex){
    var topupJson = @Html.Raw(Json.Encode(topupList));
    var list = eval(topupJson);
}

2、时间戳格式化时间格式

    function formatDateBoxFull(value) {
        if (value == null || value == '') {
            return '';
        }
        var dt = parseDate(value);
        //console.log(dt.getFullYear());
        return dt.getFullYear() == 1 ? "— —" : dt.format("yyyy-MM-dd hh:mm:ss");
    }

    var parseDate = function (timeSpan) {
        var timeSpan = timeSpan.replace('Date', '').replace('(', '').replace(')', '').replace(///g, '');
        var d = new Date(parseInt(timeSpan));
        return d;
    };

    //为Date类型拓展一个format方法,用于格式化日期
    Date.prototype.format = function (format)
    {
        var o = {
            "M+": this.getMonth() + 1, //month
            "d+": this.getDate(),    //day
            "h+": this.getHours(),   //hour
            "m+": this.getMinutes(), //minute
            "s+": this.getSeconds(), //second
            "q+": Math.floor((this.getMonth() + 3) / 3),  //quarter
            "S": this.getMilliseconds() //millisecond
        };

        if (/(y+)/.test(format))
            format = format.replace(RegExp.$1,
                (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
            if (new RegExp("(" + k + ")").test(format))
                format = format.replace(RegExp.$1,
                    RegExp.$1.length == 1 ? o[k] :
                        ("00" + o[k]).substr(("" + o[k]).length));
        return format;
    };

    运用: $("#RefundTime").val(formatDateBoxFull(list[pageIndex].RefundTime));

3、a标签点击变红,其他的恢复原状

@for (int i = 0; i < topupList.Count; i++){
var id = "TopupPage" + i;
<a id="@id" class="TopupPage" style="padding-left:5px;" onclick="TopupPage(@i)">@(i + 1)</a>
}

var alist = document.getElementsByClassName("TopupPage");
$(".TopupPage").css({color:"#000"});
$("#TopupPage"+pageIndex).css({color:"#ff0000"});   //令当前标签高亮

4、js动态时间

<label name="RealTime" id="RealTime"></label>
    $(function () {
        GetDate();
        setInterval("GetDate()", 1000);
});

    function GetDate() {
        var date = new Date();
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var day = date.getDate();
        var hour = date.getHours();
        var minute = date.getMinutes();
        var second = date.getSeconds();

        var timeStr = year + "-" +
            (month < 10 ? "0" + month : month) + "-" +
            (day < 10 ? "0" + day : day) + " " +
            (hour < 10 ? "0" + hour : hour) + ":" +
            (minute < 10 ? "0" + minute : minute) + ":" +
            (second < 10 ? "0" + second : second);
        //console.log(timeStr);
        $("#RealTime").html(timeStr);
    }

5、键值对使用

   Dictionary<int, List<DiaryEntity>> dic = new Dictionary<int, List<DiaryEntity>>();
   if (!dic.ContainsKey(year))   //判断键值对中是否存在某个键
   dic.Add(year, dataList);  
   dataList = new List<DiaryEntity>();  //添加玩list集合之后,使用new 不要使用Clare()方法,不然赋值的dic中list也会被清空
   ViewBag.DicList = dic.OrderByDescending(p => p.Key).ToDictionary(p => p.Key, o => o.Value);  //将键值对按key值降序排序

6、文件上传功能

[HttpPost]
/// <summary>
/// 上传文件
/// </summary>
/// <returns></returns>
public JsonResult ExportFile()
{
    UploadFile _uploadFile = new UploadFile();
    try
    {
        var file = Request.Files[0]; //获取选中文件
        string fileNameEx = Path.GetExtension(file.FileName);//获取扩展名
        string fileNameTrue = Path.GetFileNameWithoutExtension(file.FileName);// 获取文件名不含扩展名
        string imgType = Configs.GetValue("ImgType").ToUpper();

        if (file == null || string.IsNullOrEmpty(file.FileName) || file.ContentLength == 0)
        {
            _uploadFile.code = -1;
            _uploadFile.data = new { src = "" };
            _uploadFile.msg = "上传出错!未检测到文件";
            return Json(_uploadFile);
        }

        if (!imgType.Contains(fileNameEx.ToUpper().Replace(".", "")))
        {
            _uploadFile.code = -1;
            _uploadFile.data = new { src = "" };
            _uploadFile.msg = "上传出错!图片格式只支持"+ imgType;
            return Json(_uploadFile);
        }

        string filePathName = string.Empty;
        //定义本地路径位置
        string localPath = Server.MapPath("~/Upload/ArticleUploadImg/");
        string tmpName = Server.MapPath("~/Upload/ArticleUploadImg/");
        var tmp = file.FileName;
        var tmpIndex = 0;

        //判断是否存在相同文件名的文件 相同累加1继续判断  
        while (System.IO.File.Exists(tmpName + tmp))
        {
            tmp = fileNameTrue + "_" + ++tmpIndex + fileNameEx;
        }

        //不带路径的最终文件名  
        filePathName = tmp;

        if (!Directory.Exists(localPath))
            Directory.CreateDirectory(localPath);
        file.SaveAs(Path.Combine(tmpName, filePathName));   //保存图片(文件夹)  

        _uploadFile.code = 0;
        _uploadFile.data = new { src = Path.Combine("/Upload/ArticleUploadImg/", filePathName), title = Path.GetFileNameWithoutExtension(filePathName) };   
        _uploadFile.msg = "上传成功";
        return Json(_uploadFile);
    }
    catch (Exception ex)
    {
        return Json(_uploadFile, JsonRequestBehavior.AllowGet);
    }
}

7、List 合并操作

List<int> listA = new List<int> { 1, 4, 8, 9, 7, 8, 3 };
List<int> listB = new List<int> { 13, 4, 17, 29, 2 };
List<int> ResultA = listA.Union(listB).ToList(); //剔除重复项
List<int> ResultB = listA.Concat(listB).ToList(); //保留重复项

8、Select2插件实现多选

1)引入select2.css和select2.js

<link href="~/Areas/Admin/Content/js/select2/select2.min.css" rel="stylesheet" />
<script src="~/Areas/Admin/Content/js/select2/select2.min.js"></script>

2)HTML:

<select name="slt_bot" id="slt_bot" multiple="multiple"></select>

3)JS:

$("#slt_bot").select2({
      language: "zh-CN",
      minimumInputLength: 0,
      placeholder: "可多选",//默认值
      allowClear: true,
  });

  $.ajax({
      type: "post",
      dataType: "json",
      url: "/Home/GetBotListSelect2",
      success: function (data) {
          $.each(data, function (i) {
              //console.log("<option value='" + data[i].UserId + "'>" + data[i].UserName + "</option>");
              $("#slt_bot").append("<option value='" + data[i].UserId + "'>" + data[i].UserName + "</option>");
          })
      }
  })

  $("#slt_bot").change(function () {
      console.log($("#slt_bot").val())
  })

9、js正负数正则

isMoney("0.12.3");

function isMoney(s) {
  //金额 只允许正数
  //var exp = /(^[1-9]([0-9]+)?(.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9].[0-9]([0-9])?$)/;
  //金额 允许正(+)负数
  //var exp = /(^([+-]?)[1-9]([0-9]+)?(.[0-9]{1,2})?$)|(^([+-]?)(0){1}$)|(^([+-]?)[0-9].[0-9]([0-9])?$)/;

  //金额 允许正负数
  var exp = /(^([-]?)[1-9]([0-9]+)?(.[0-9]{1,2})?$)|(^([-]?)(0){1}$)|(^([-]?)[0-9].[0-9]([0-9])?$)/;
  if (exp.test(s)) {
      console.log("true" + s)
  } else {
      console.log("false" + s)
  }
}

10、接口请求

POST

var client = new RestClient(BaseUrl);
    var request = new RestRequest("/api/business/batchreadings", Method.POST);
    request.AddHeader("token", token);
    request.AddHeader("time", beginTime); //起始时间“yyyy-mm-dd hh:mi:ss”如: 2018-11-05 10:00:00
    request.AddHeader("endtime", endTime); //结束时间“yyyy-mm-dd hh:mi:ss”如: 2018-11-05 10:00:00
    request.RequestFormat = DataFormat.Json; 
try
{
   var response = client.Execute<object>(request);
   if (response.StatusCode == HttpStatusCode.OK)
    {
       var msgTest = response.Content;
    }
 }
catch (Exception ex)
{
    result.errmsg = ex.Message;
}

GET

var client = new RestClient(BaseUrl);
RestRequestrequest = new RestRequest("/DataPass/SysAppletWashingPosServiceV1", Method.GET);
request.AddParameter("sign", signature);
request.AddParameter("code", value);
request.AddParameter("sid", "20170427000001");
request.RequestFormat = DataFormat.Json;

try
{
    var requestResponse = client.Execute<AuthorizationCenterResponse>(request);
    if (requestResponse.StatusCode == HttpStatusCode.OK)
    {
        msgTest = "请求接口返回数据Content:" + requestResponse.Content;

    }
}
catch (Exception ex)
{
    result.errmsg = ex.Message;
}

11、DataTable分隔成多个table

private static List<DataTable> DataTableSplite(DataTable dt, int modcounts)
{
     int counts = dt.Rows.Count / modcounts;  //  取整数个数
     counts = dt.Rows.Count % modcounts == 0 ? counts : counts + 1;
     List<DataTable> list = new List<DataTable>();

     int index = 0;
     for (int i = 0; i < counts; i++)
     {
         list.Add(dt.AsEnumerable().Skip(index * modcounts).Take(modcounts).CopyToDataTable());
         index++;
     }
     return list;
}

12、list集合比较差异

var oldMembersSipList = new List<string> { "q", "w", "e" };
var newMemberList = new List<string> { "a", "w", "d", "e" };

//old和new中同时存在
var bothExist = oldMembersSipList.Where(a => newMemberList.Exists(a.Contains)).ToList();
//old中存在,new中不存在
var oldExits = oldMembersSipList.Where(a => !newMemberList.Exists(a.Contains)).ToList();
//new中存在,old中不存在
var newExits = newMemberList.Where(a => !oldMembersSipList.Exists(a.Contains)).ToList();
原文地址:https://www.cnblogs.com/dennisdong/p/13410073.html