在JQGrid中显示CategoryName与产品名称和价格

本文关键字:产品名 JQGrid 显示 CategoryName | 更新日期: 2023-09-27 18:17:34

我的产品型号如下

public class Product
{
public int ProductId { get; set; }
public string ProductName { get; set; }
public int CategoryId {get;set;}
public float Price { get; set; }
public Category category { get; set; }
}

我已经在下面的方法中读取了类别ID和类别名称,现在想要在JQGrid中显示产品名称,类别名称和价格,但它只显示产品名称和价格,而不是CayegoryName。

public JsonResult ShowProducts(string sidx, string sord, int page, int rows)
        {
            int pageIndex = Convert.ToInt32(page) - 1;
            int pageSize = rows;
            BusinessLayer BusLayer = new BusinessLayer();
            List<Product> ProdList = new List<Product>();
            ProdList = BusLayer.ReadProducts();
            foreach (var Prd in ProdList)
            {
                Prd.category = BusLayer.GetCategoryById(Prd.CategoryId);                
            }
            int recordCount = ProdList.Count;
            var totalPages = (int)Math.Ceiling((float)recordCount / (float)rows);
           var jsonData = new
            {
                total = totalPages,
                records = recordCount,
                rows = ProdList                
            };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }

脚本显示如下,

$("#grid").jqGrid({
        url: "/Admin/ShowProducts",
        datatype: 'json',
        mtype: 'Get',
        colNames: ['Id', 'Product Name', 'Category Name', 'Price', 'CatId'],
        colModel: [
            { key: true, hidden: true, name: 'Id', index: 'Id', editable: true },
            { key: false, name: 'ProductName', index: 'ProductName', editable: true },
            { key: false, name: 'CategoryName', index: 'CategoryName', editable: true },
            { key: false, name: 'Price', index: 'Price', editable: true },
            { key: true, hidden: true, name: 'CATId', index: 'CatId', editable: true },
            ],
        pager: jQuery('#pager'),
        rowNum: 5,
......
......
......

在JQGrid中显示CategoryName与产品名称和价格

在Product中,ProductName是字符串类型,而Category属性不是字符串类型。因此,应该将Category转换为字符串类型以保存Category名称。

除此之外,在jqGrid properties中,colModel名称表示到属性的直接映射。对于category, name应该是category而不是category name。更新如下:

$("#grid").jqGrid({
        url: "/Admin/ShowProducts",
        datatype: 'json',
        mtype: 'Get',
        colNames: ['Id', 'Product Name', 'Category Name', 'Price', 'CatId'],
        colModel: [
            { key: true, hidden: true, name: 'Id', index: 'Id', editable: true },
            { key: false, name: 'ProductName', index: 'ProductName', editable: true },
            { key: false, name: 'Category', index: 'Category', editable: true },
            { key: false, name: 'Price', index: 'Price', editable: true },
            { key: true, hidden: true, name: 'CATId', index: 'CatId', editable: true },
            ],
        pager: jQuery('#pager'),
        rowNum: 5,