【发布时间】:2010-09-20 14:59:35
【问题描述】:
我正在使用 jqGrid 在页面上显示一些数据。在控制器操作中,我们使用匿名对象来表示 jqGrid 需要的数据。我的问题是,有没有一种方法可以创建一个强类型对象来表示我们使用 Json() 发送的 jqGrid 数据?
这样做的主要原因是我们可以对发送给它的对象进行单元测试。
谢谢!
编辑:
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult GridData(FormCollection form, string alias, string location, string state)
{
int pageSize = Convert.ToInt32(form["rows"]);
int pageIndex = Convert.ToInt32(form["page"]) - 1;
var deviceList = this._device.GetList(CreateFilter(location,alias,state),this._securityCache.GetSecurityContext(),pageSize,pageIndex);
int totalResults = deviceList.TotalRecords;
int totalPages = (int)Math.Ceiling((float)totalResults / (float)pageSize);
var jsonData = new {
total = totalPages,
page = pageIndex + 1,
records = totalResults,
rows = (from device in deviceList.Data
select new {i = device.Alias,cell = new string[]{device.Alias,device.Location,device.RatePlan,device.State,device.DateCreated.ToString()}}).ToArray()
};
return Json(jsonData);
上面的方法有效,但我们不能对传递给 Json() 方法的数据进行单元测试。
var newJsonData = new JsonJQGridReturnData();
newJsonData.total = totalPages;
newJsonData.page = pageIndex + 1;
newJsonData.records = totalResults;
List<JsonJQGridRow> list = new List<JsonJQGridRow>();
foreach (var device in deviceList.Data)
{
list.Add(new JsonJQGridRow(device.Alias, new string[] { device.Alias, device.Location, device.RatePlan, device.State, device.DateCreated.ToString() }));
}
newJsonData.rows = list.ToArray();
_cookieHelper.SaveCookie("DeviceListIndex", this._securityCache.GetSecurityContext().UserID.ToString(), COOKIE_PAGE_SIZE_KEY, pageSize.ToString());
return Json(newJsonData);
}
这是我试图将这些包装成强类型对象的糟糕尝试。不幸的是,运行它会在 jqGrid 文件中给我一个“u is undefined”。我怀疑这是因为传入的 json 格式不正确。这是课程......
[DataContract]
public class JsonJQGridReturnData
{
[DataMember]
public int total { get; set; }
[DataMember]
public int page { get; set; }
[DataMember]
public int records { get; set; }
[DataMember]
public JsonJQGridRow[] rows { get; set; }
}
[DataContract]
public class JsonJQGridRow
{
public JsonJQGridRow(string i, string[] columns)
{
this.i = i;
this.cells = columns;
}
[DataMember]
public string i { get; set; }
[DataMember]
public string[] cells { get; set; }
}
【问题讨论】:
-
我怀疑您的问题中缺少某些内容。你想要一个强类型的 JsonResult 吗?比如,一个 JQGridResult?
标签: asp.net-mvc json jqgrid