C# MVC绑定 List到bootstrap-table列表

时间:2021-12-24 22:48:27

1.Dapper返回List<dynamic>对象

    /// <summary>
/// 获取候选人推荐的分页数据
/// </summary>
/// <param name="page"></param>
/// <param name="pageSize"></param>
/// <param name="candidateName"></param>
/// <param name="allRowsCount"></param>
/// <returns></returns>
public List<dynamic> GetCandidateRecommendPage(int page, int pageSize, string candidateName, out long allRowsCount)
{
var sql = @"SELECT c.Name,c.birthday,c.CVId FROM dbo.Candidate c ";
var allRowsCountSql = @"SELECT COUNT(0) FROM dbo.Candidate"; var ret = base.DBSession.Connection.GetPage<dynamic>(page, pageSize, out allRowsCount, sql, null, allRowsCountSql).ToList();
return ret;
}

2.Controller层使用Newtonsoft.Json序列化

        public JsonResult GetRecommends(int page, int pageSize, string candidatename)
{
var allRowsCount = 0L; var list = RpoJobRepository.NewInstance.GetCandidateRecommendPage(page, pageSize, candidatename, out allRowsCount); return base.NewtonsoftJson(new { total = allRowsCount, rows = list }, JsonRequestBehavior.AllowGet);
}
   protected JsonResult NewtonsoftJson(object data, JsonRequestBehavior behavior)
{
return new NewtonsoftJsonResult
{
Data = data,
JsonRequestBehavior = behavior,
};
}
 /// <summary>
/// Newtonsoft序列化方式
/// </summary>
public class NewtonsoftJsonResult : JsonResult
{
/// <summary>
/// 重写执行视图
/// </summary>
/// <param name="context">上下文</param>
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
} HttpResponseBase response = context.HttpContext.Response; if (string.IsNullOrEmpty(this.ContentType))
{
response.ContentType = this.ContentType;
}
else
{
response.ContentType = "application/json";
} if (this.ContentEncoding != null)
{
response.ContentEncoding = this.ContentEncoding;
} if (this.Data != null)
{
var jsonString = JsonConvert.SerializeObject(this.Data);
response.Write(jsonString);
}
}

3.View层像绑定对象列表一样绑定

 columns: [{
checkbox: true
},
{
field: 'Name',
title: '姓名',
formatter: this.nameFormatter }]

这里的field和第一步里查询的列名一致。

总结

1.dapper的 base.DBSession.Connection.GetPage<dynamic>方法返回的是DapperRow列表,DapperRow 继承 Dictionary<string, object>

2.controller返回对象时做json序列化,如果使用JavaScriptSerializer,结果是字典的JSON格式,如:

"total":143694,"rows":[[{"Key":"Name","Value":"赵保龙"},{"Key":"birthday","Value":"\/Date(107712000000)\/"},
使用Newtonsoft.Json.JsonConvert 序列化是对象格式,如:
{"total":143694,"rows":[{"Name":"璧典繚榫�","birthday":"1973-06-01T00:00:00","CVId":"JR027902222R90250000000"},{"Name":"閮厛鐢�","birthday":"1981-11-01T00:00:00","CVId":null},

3.使用动态类型不必再去定义ViewModel类了,节省很多时间。

4.还有一种方式是使用DataTable也可以达到相同目的,没做尝试。