【问题标题】:LINQ to list<AJAX> to be used in DataTableLINQ to list<AJAX> 要在 DataTable 中使用
【发布时间】:2016-12-01 22:00:58
【问题描述】:

我正在尝试执行 LINQ 查询以填充 AJAX 列表,然后我将返回该列表以在我的视图中的 DataTable 中使用。

当我没有尝试实现 AJAX 并且只是将它放置在模型中并在循环中渲染表中的每一行时,我已经完成了这项工作。然而,这对资源的要求非常高,并且在我的较大查询中呈现页面需要很长时间。

所以我尝试实现 AJAX,但是 LINQ 返回 NULL。我知道我可以正确获取数据,因为我已经实现了一个测试用例,它返回一个简单的 AJAX 小样本,但是即使这样它也不会因为某种原因填充我的数据表。

简而言之,我需要:修复我的 LINQ 以列出使用它来填充数据表

这是我的控制器:

public class stockAJAX
{
    public int StockId { get; set; }
    public string ProductGroup { get; set; }
    public string GroupType { get; set; }
    public string ItemType { get; set; }
    public string Model { get; set; }
    public string SerialNo { get; set; }
    public string NR { get; set; }
    public string Status { get; set; }
    public string Description { get; set; }
    public string DateArrived { get; set; }
    public int? CurrentLocation { get; set; }
    public string TerminalId { get; set; }
}

public class TableController : Controller
{
    List<stockAJAX> stock = new List<stockAJAX>();
    stockAJAX ajaxTemp = new stockAJAX();
    static string csv;


[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
public JsonResult getAJAX(System.Web.Mvc.FormCollection collection)
{
    //Recieve Data from the Select Company DropDownList
    string selectedList = collection["list"];
    //Recieve Data from the Select GroupType DropDownList
    string selectedGroupType = collection["grouptype"];
    //Recieve Data from the Show All Stock checkbox
    string selectedAmount = collection["amount"];

    //A list of type <stock> has its value recieved from the function which computes which query to use and then executes it.
    stock = returnList(selectedGroupType, selectedList, selectedAmount);

    if (stock == null)
    {
        System.Windows.Forms.MessageBox.Show("NULL AJAX");

        stockAJAX stock1 = new stockAJAX();
        stock1.StockId = 0;
        stock1.ProductGroup = " ";
        stock1.GroupType = " ";
        stock1.ItemType = " ";
        stock1.Model = " ";
        stock1.SerialNo = " ";
        stock1.NR = " ";
        stock1.Status = " ";
        stock1.Description = " ";
        stock1.DateArrived = " ";
        stock1.CurrentLocation = 0;
        stock1.TerminalId = " ";
        return Json(stock1, JsonRequestBehavior.AllowGet);
    }


    return Json(stock, JsonRequestBehavior.AllowGet);
}

//Function that grabs the data for the DataTable, and the two DropDownLists, the two DropDownLists are return through ViewData[] and the DataTable data is returned via Model
//Takes three strings which are taken from Form Data
public List<stockAJAX> returnList(string selectedGroupType, string selectedList, string selectedAmount)
{
    //List of type <stock> this will contain all of the data to be put into the DataTable



    //Namespace utilising the TableEntities connection to the Entity Framework
    using (TableEntities context = new TableEntities())
    {
        //Lists which will contain data for the DropDownLists
        IList<SelectListItem> ddl = new List<SelectListItem>();
        IList<SelectListItem> ddl2 = new List<SelectListItem>();

        //Temp list of strings, used to grab data from the Entity to be placed into the dropdownlists
        List<string> stocktemp = null;

        //Query for the ProductGroup DropDownList
        stocktemp = (from c in context.stocks
                     select c.ProductGroup
                    ).Distinct().ToList();
        foreach (string item in stocktemp)  //Places data received in the SelectList as items
        {
            if (item == selectedList && item != null)       //Tests to see if the Item was selected in the last view, if so is set as default
                ddl.Add(new SelectListItem() { Text = item, Selected = true });
            else if (item != null)
                ddl.Add(new SelectListItem() { Text = item });
        }
        ViewData["list"] = ddl;         //PLaces the SelectList in the ViewData[]


        //Query for the GroupType DropDownList
        stocktemp = (from c in context.stocks
                     select c.GroupType
                    ).Distinct().ToList();
        foreach (string item in stocktemp)//Tests to see if the Item was selected in the last view, if so is set as default
        {
            if (item == selectedGroupType && item != null)
                ddl2.Add(new SelectListItem() { Text = item, Selected = true });
            else if (item != null)
                ddl2.Add(new SelectListItem() { Text = item });
        }
        ViewData["grouptype"] = ddl2;   //PLaces the SelectList in the ViewData[]

        //If the user selected to show all data, omits the Take(1000) function
        if (selectedAmount == "true")
        {
            //If the Value is null for both, then it will return no data.
            //This case is if the User selected the default non-value option for each
            if (selectedList == null && selectedGroupType == null)
            {
                stock = (from c in context.stocks
                         select new stockAJAX
                         {
                             StockId = c.StockId,
                             ProductGroup = c.ProductGroup,
                             GroupType = c.GroupType,
                             ItemType = c.ItemType,
                             Model = c.Model,
                             SerialNo = c.SerialNo,
                             NR = c.NR,
                             Status = c.Status.ToString(),
                             Description = c.Description,
                             DateArrived = c.DateArrived.ToString(),
                             CurrentLocation = c.CurrentLocation,
                             TerminalId = c.TerminalId,
                         }
                        ).ToList();
            }
            else if (selectedGroupType == "grouptype=Select+GroupType" || selectedGroupType == null || selectedGroupType == "")     //If SelecteGroupType is NULL, then no value was selected for Select GroupType
            {
                if (selectedList == null || selectedList == "")     //if selectedList is also NULL return nothing
                {
                    stock = (from c in context.stocks
                             select new stockAJAX
                             {
                                 StockId = c.StockId,
                                 ProductGroup = c.ProductGroup,
                                 GroupType = c.GroupType,
                                 ItemType = c.ItemType,
                                 Model = c.Model,
                                 SerialNo = c.SerialNo,
                                 NR = c.NR,
                                 Status = c.Status.ToString(),
                                 Description = c.Description,
                                 DateArrived = c.DateArrived.ToString(),
                                 CurrentLocation = c.CurrentLocation,
                                 TerminalId = c.TerminalId,
                             }
                        ).ToList();
                }
                else                    //Else, if selectedList is not null, return data from query using selectedList as the testing for ProductGroup
                {
                    stock = (from c in context.stocks
                             where c.ProductGroup == selectedList
                             select new stockAJAX
                             {
                                 StockId = c.StockId,
                                 ProductGroup = c.ProductGroup,
                                 GroupType = c.GroupType,
                                 ItemType = c.ItemType,
                                 Model = c.Model,
                                 SerialNo = c.SerialNo,
                                 NR = c.NR,
                                 Status = c.Status.ToString(),
                                 Description = c.Description,
                                 DateArrived = c.DateArrived.ToString(),
                                 CurrentLocation = c.CurrentLocation,
                                 TerminalId = c.TerminalId,
                             }
                        ).ToList();
                }
            }
            else if (selectedList == "list=Select+Company" || selectedList == null || selectedList == "")       //if select list is null, then no value was selected for Select Company
            {
                stock = (from c in context.stocks
                         where c.GroupType == selectedGroupType
                         select new stockAJAX
                         {
                             StockId = c.StockId,
                             ProductGroup = c.ProductGroup,
                             GroupType = c.GroupType,
                             ItemType = c.ItemType,
                             Model = c.Model,
                             SerialNo = c.SerialNo,
                             NR = c.NR,
                             Status = c.Status.ToString(),
                             Description = c.Description,
                             DateArrived = c.DateArrived.ToString(),
                             CurrentLocation = c.CurrentLocation,
                             TerminalId = c.TerminalId,
                         }
                        ).ToList();
            }
            else                        //else if grouptype is not null, retrun data from query using groupType as the testing for GroupType
            {
                stock = (from c in context.stocks
                         where c.ProductGroup == selectedList
                         where c.GroupType == selectedGroupType
                         select new stockAJAX
                         {
                             StockId = c.StockId,
                             ProductGroup = c.ProductGroup,
                             GroupType = c.GroupType,
                             ItemType = c.ItemType,
                             Model = c.Model,
                             SerialNo = c.SerialNo,
                             NR = c.NR,
                             Status = c.Status.ToString(),
                             Description = c.Description,
                             DateArrived = c.DateArrived.ToString(),
                             CurrentLocation = c.CurrentLocation,
                             TerminalId = c.TerminalId,
                         }
                        ).ToList();
            }
        }
        else        //If Show All was not checked, then select top 1000 ordered by descending date
        {
            //If the Value is null for both, then it will return no data.
            //This case is if the User selected the default non-value option for each
            if (selectedList == null && selectedGroupType == null)
            {
                stock = null;
            }
            else if (selectedGroupType == "grouptype=Select+GroupType" || selectedGroupType == null || selectedGroupType == "")     //If SelecteGRoupType is NULL, then no value was selected for Select GroupType
            {
                if (selectedList == null || selectedList == "")     //if selectedList is also NULL return nothing
                {
                    stock = null;
                }
                else                //Else, if selectedList is not null, return data from query using selectedList as the testing for ProductGroup
                {
                    stock = (from c in context.stocks
                             where c.ProductGroup == selectedList
                             orderby c.DateArrived descending
                             select new stockAJAX
                         {
                             StockId = c.StockId,
                             ProductGroup = c.ProductGroup,
                             GroupType = c.GroupType,
                             ItemType = c.ItemType,
                             Model = c.Model,
                             SerialNo = c.SerialNo,
                             NR = c.NR,
                             Status = c.Status.ToString(),
                             Description = c.Description,
                             DateArrived = c.DateArrived.ToString(),
                             CurrentLocation = c.CurrentLocation,
                             TerminalId = c.TerminalId,
                         }
                        ).Take(1000).ToList();
                }
            }
            else if (selectedList == "list=Select+Company" || selectedList == null || selectedList == "")   //if select list is null, then no value was selected for Select Company
            {
                stock = (from c in context.stocks
                         where c.GroupType == selectedGroupType
                         orderby c.DateArrived descending
                         select new stockAJAX
                         {
                             StockId = c.StockId,
                             ProductGroup = c.ProductGroup,
                             GroupType = c.GroupType,
                             ItemType = c.ItemType,
                             Model = c.Model,
                             SerialNo = c.SerialNo,
                             NR = c.NR,
                             Status = c.Status.ToString(),
                             Description = c.Description,
                             DateArrived = c.DateArrived.ToString(),
                             CurrentLocation = c.CurrentLocation,
                             TerminalId = c.TerminalId,
                         }
                        ).Take(1000).ToList();
            }
            else                //else if grouptype is not null, retrun data from query using groupType as the testing for GroupType
            {
                stock = (from c in context.stocks
                         where c.ProductGroup == selectedList
                         where c.GroupType == selectedGroupType
                         orderby c.DateArrived descending
                         select new stockAJAX
                         {
                             StockId = c.StockId,
                             ProductGroup = c.ProductGroup,
                             GroupType = c.GroupType,
                             ItemType = c.ItemType,
                             Model = c.Model,
                             SerialNo = c.SerialNo,
                             NR = c.NR,
                             Status = c.Status.ToString(),
                             Description = c.Description,
                             DateArrived = c.DateArrived.ToString(),
                             CurrentLocation = c.CurrentLocation,
                             TerminalId = c.TerminalId,
                         }
                        ).Take(1000).ToList();
            }
        }
    }


    //return the value to be used by the DataTable
    return stock;
}

//Accept GET and POST
[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
public ActionResult Index(System.Web.Mvc.FormCollection collection)
{
    //DateTime lastMonth = DateTime.Today.AddMonths(-6);

    //Recieve Data from the Select Company DropDownList
    string selectedList = collection["list"];
    //Recieve Data from the Select GroupType DropDownList
    string selectedGroupType = collection["grouptype"];
    //Recieve Data from the Show All Stock checkbox
    string selectedAmount = collection["amount"];

    //A list of type <stock> has its value recieved from the function which computes which query to use and then executes it.
    returnList(selectedGroupType, selectedList, selectedAmount);

    //Returns the view
    return View();

这是我的 View Javascript:

var Json = [
    { StockId: 0, 
    ProductGroup: 0, 
    GroupType: 0,
    ItemType: 0 ,
    Model: 0 ,
    SerialNo: 0,
    NR: 0 ,
    Status: 0,
    Description: 0,
    DateArrived: 0 ,
    CurrentLocation: 0 ,
    TerminalId: 0,
    },
    ];

    $("#myTable").DataTable({
        "JQueryUI": true,
        "stateSave": true,
        "ajax": $.ajax({
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            type: 'GET',
            url: '/Table/getAJAX',
            data: Json,
            success: function(Json)
            {
                if (Json.length == 0 || Json == null)
                    alert(post);
                var _len = Json.length, post, i;

                for (i = 0; i < _len; i++) {
                    post = Json[i];
                    alert(post);
                }
            },
            failure: function () { alert("unavailable"); },
        })
    });
    $('#loading').hide();
    $('#myTable').show();

这是我的视图数据表:

<div class="filter">
<form class="my-form" method="post" action="~/Table/Index">
    <br />
    @Html.DropDownList("list", "Select Company")
    @Html.DropDownList("grouptype", "Select GroupType")
    <br />
    <button input type="submit"> Submit </button>
    <input type="checkbox" name="amount" id="amount" value="true"><p2>Show All Company Stock</p2>
    <br /><br />
</form>
</div>
<table class="table-fill" id="myTable">
        <thead>
            <tr>
                <th>
                    <p1>Stock Id</p1>
                </th>
                <th>
                    <p1>Product Group</p1>
                </th>
                <th>
                    <p1>Group Type</p1>
                </th>
                <th>
                    <p1>Item Type</p1>
                </th>
                <th>
                    <p1>Model</p1>
                </th>
                <th>
                    <p1>Serial No</p1>
                </th>
                <th>
                    <p1>NR</p1>
                </th>
                <th>
                    <p1>Status</p1>
                </th>
                <th>
                    <p1>Description</p1>
                </th>
                <th>
                    <p1>Date Arrived</p1>
                </th>
                <th>
                    <p1>Current Location</p1>
                </th>
                <th>
                    <p1>Terminal ID</p1>
                </th>
            </tr>
        </thead>
        <tfoot>
            <tr>
                <th>Id</th>
                <th>Product</th>
                <th>Group</th>
                <th>Item</th>
                <th>Model</th>
                <th>Serial</th>
                <th>NR</th>
                <th>Status</th>
                <th>Descr</th>
                <th>Date</th>
                <th>Location</th>
                <th>T-ID</th>
            </tr>
        </tfoot>


    </table>

我删除了一些我认为对可读性不重要的功能。

非常感谢。

编辑:另一个关键事实是我的数据表的成功或失败功能没有执行。

编辑: 我也摆脱了 ViewData 的东西,现在它可以工作了(在 POSTMAN 中测试)!但是,当我尝试查询所有数据时,它超出了 JSON 的最大可能限制:2147483644。

所以我尝试了一个较小的查询,如果我使用 POSTMAN 可以正确显示。但是它没有显示在表格中,我收到错误:

http://localhost:51326/Table/Index?draw=1&columns%5B0%5D%5Bdata%5D=0&column…art=0&length=10&search%5Bvalue%5D=&search%5Bregex%5D=false&_=1480633376897 加载资源失败:服务器响应状态为 404(未找到)

目前正在解决此问题。

【问题讨论】:

  • 单步执行时会发生什么?
  • @h2015 它不会抛出任何错误或任何东西,它可以正常执行。但是,从 LINQ 中提取的数据为空。
  • 5 星了解您的调试器以及如何使用它
  • 然而另一个关键事实是我的数据表的成功或失败功能没有执行。
  • 您无法真正在 ajax 调用中访问 ViewData。我没有进一步查看是否还有更多问题。 ajax 调用是一个单独的请求,具有单独的请求/响应。

标签: javascript c# asp.net ajax linq


【解决方案1】:

重写函数(删除了属于不同函数的下拉填充和 DataView 内容):

public List<stockAJAX> returnList(string selectedGroupType, string selectedList, string selectedAmount)
{
    using (TableEntities context = new TableEntities())
    {
        // Do base query
        IQueryable<stock> stocks = context.stocks.AsQueryable();

        // Do filtering here
        if (selectedList == null && selectedGroupType == null)
        {
          // return all the records
        }
        else if (selectedGroupType == "grouptype=Select+GroupType" || selectedGroupType == null || selectedGroupType == "")     //If SelecteGroupType is NULL, then no value was selected for Select GroupType
        {
            if (selectedList == null || selectedList == "")     //if selectedList is also NULL return nothing
            {
              // return all the records
            }
            else                    //Else, if selectedList is not null, return data from query using selectedList as the testing for ProductGroup
            {
                stocks = stocks.Where(c=>c.ProductGroup == selectedList);
            }
        }
        else if (selectedList == "list=Select+Company" || selectedList == null || selectedList == "")       //if select list is null, then no value was selected for Select Company
        {
            stocks = stocks.Where(c=>c.GroupType == selectedGroupType);
        }
        else                        //else if grouptype is not null, retrun data from query using groupType as the testing for GroupType
        {
            stocks = stocks
              .Where(c=>c.ProductGroup == selectedList)
              .Where(c=>c.GroupType == selectedGroupType);
        }

      // Apply limit
      if (selectedAmount != "true") 
      {
        stocks = stocks
          .OrderByDescending(c=>c.DateArrived)
          .Take(1000);
      }

      // Do projection to DTO
      var result = stocks.Select(c=>new stockAJAX
      {
        StockId = c.StockId,
        ProductGroup = c.ProductGroup,
        GroupType = c.GroupType,
        ItemType = c.ItemType,
        Model = c.Model,
        SerialNo = c.SerialNo,
        NR = c.NR,
        Status = c.Status.ToString(),
        Description = c.Description,
        DateArrived = c.DateArrived.ToString(),
        CurrentLocation = c.CurrentLocation,
        TerminalId = c.TerminalId,
      }).ToList();
    }

    //return the value to be used by the DataTable
    return result;
}

【讨论】:

  • 谢谢!当我解决让我的 DataTable 现在加载我的 AJAX 的新问题时,我将实现这一点。
【解决方案2】:

我通过像建议的那样删除对 ViewData 的引用来修复它。

[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
        public JsonResult getAJAX()
        {
            using (TableEntities context = new TableEntities())
            {
                stock = (from c in context.stocks
                         select new stockAJAX
                         {
                             StockId = c.StockId,
                             ProductGroup = c.ProductGroup,
                             GroupType = c.GroupType,
                             ItemType = c.ItemType,
                             Model = c.Model,
                             SerialNo = c.SerialNo,
                             NR = c.NR,
                             Status = c.Status.ToString(),
                             Description = c.Description,
                             DateArrived = c.DateArrived.ToString(),
                             CurrentLocation = c.CurrentLocation,
                             TerminalId = c.TerminalId,
                         }
                                    ).Take(1000).ToList();
            }

            return Json(stock, JsonRequestBehavior.AllowGet);
        }

但是,DataTable 现在卡在处理中。见问题: Datatable stuck on "Processing" on initial load

【讨论】:

    猜你喜欢
    • 2013-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多