使用Linq将剑道网格绑定到MVC 5中的EF查询

本文关键字:MVC 中的 EF 查询 绑定 Linq 网格 使用 | 更新日期: 2023-09-27 18:19:26

开始。我是MVC和EF的新手,正在尝试构建我的第一个项目,该项目将允许对公司信用卡交易进行批量编辑。剑道网格似乎是完成这项工作的最佳方法。

查询采用在查询字符串中传递的两个参数(accountID和语句日期)。我已经能够将网格绑定到一个模型,并让它显示正确的事务。接下来,我需要配置它来进行批量编辑。我被卡住了。目前有两个问题:

  1. 无法获取要绑定到Transaction_Read方法的网格(返回空网格)。index方法可以将事务绑定到网格,但不能在Json中绑定
  2. 无法获取网格以进行批量更新。它会一直到.SaveChanges函数,但实际上不会更新任何字段

我的型号:

namespace intranetMVC.Models
{
using System;
using System.Collections.Generic;

public partial class CorpCardTransaction
{
    public int ID { get; set; }
    public System.DateTime ImportDate { get; set; }
    public string AccountID { get; set; }
    public string CardHolderName { get; set; }
    //[DataType(DataType.Date)]
    public Nullable<System.DateTime> StatementDate { get; set; }
    public Nullable<short> StatementRecordNum { get; set; }        
    public Nullable<System.DateTime> PostDate { get; set; }        
    public Nullable<System.DateTime> TranDate { get; set; }
    public string Payee { get; set; }
    public string Description { get; set; }
    public Nullable<decimal> Amount { get; set; }
    public string GL_Account { get; set; }
    public Nullable<short> BranchCode { get; set; }
    public Nullable<bool> Receipt { get; set; }        
    public Nullable<System.DateTime> BackDate { get; set; }
    public Nullable<System.DateTime> SubmitDate { get; set; }
    public Nullable<System.DateTime> ProcessDate { get; set; }
    public string MemberNum { get; set; }
    public string Username { get; set; }
}
}

CorpCardTransactionsController.cs

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using intranetMVC.Models;
using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;
using Microsoft.AspNet.Identity;
namespace intranetMVC.Controllers
{
public class CorpCardTransactionsController : Controller
{
    private ExpenseReportingEntities db = new ExpenseReportingEntities();       
    public ActionResult Index(string AccountID, DateTime StatementDate)
    {
        //var loginName = System.Security.Principal.WindowsIdentity.GetCurrent().Name.Split('''');
        //var username = loginName.Last() + "@xxxx.com";
        var username = "xxxx@xxxx.com";
        var stmtDate = StatementDate;
        var q = from b in db.CorpCardTransactions
                where b.Username == username && b.StatementDate == StatementDate && b.AccountID == AccountID && !b.SubmitDate.HasValue
                select b;
        return View(q.ToList());            
    }
    [HttpGet]
    public ActionResult Transaction_Read([DataSourceRequest] DataSourceRequest request, string AccountID, DateTime StatementDate)
    {
        //var loginName = System.Security.Principal.WindowsIdentity.GetCurrent().Name.Split('''');
        //var username = loginName.Last() + "@xxxx.com";
        var username = "xxxx@xxxx.com";
        var stmtDate = StatementDate;
        var q = from b in db.CorpCardTransactions
                where b.Username == username && b.StatementDate == StatementDate && b.AccountID == AccountID && !b.SubmitDate.HasValue
                select b;            
        return View(q.ToList());
        //IQueryable<CorpCardTransaction> transactions = q.ToList();
        //DataSourceResult result = transactions.ToDataSourceResult(result);
        //return Json(result);
    }
    [HttpPost]
    public ActionResult Transaction_Update([DataSourceRequest]DataSourceRequest request, [Bind(Prefix = "models")]IEnumerable<CorpCardTransaction> corpCardTransaction)
    {
        var entities = new List<CorpCardTransaction>();
        if (ModelState.IsValid)
        {
            using (db)
            {
                foreach (var transaction in corpCardTransaction)
                {
                    var entity = new CorpCardTransaction
                    {
                        ID = transaction.ID,
                        Description = transaction.Description,
                        GL_Account = transaction.GL_Account,
                        BranchCode = transaction.BranchCode,
                        Receipt = transaction.Receipt
                    };
                    entities.Add(entity);
                    db.CorpCardTransactions.Attach(entity);
                    db.Entry(entity).State = EntityState.Modified;
                }
                db.SaveChanges();
            }
        }
        return Json(entities.ToDataSourceResult(request, ModelState, transaction => new CorpCardTransaction
        {
            ID = transaction.ID,
            Description = transaction.Description,
            GL_Account = transaction.GL_Account,
            BranchCode = transaction.BranchCode,
            Receipt = transaction.Receipt
        }));
    }
}

}

index.cshtml查看

@*@model IEnumerable<intranetMVC.Models.CorpCardTransaction>*@
@{
ViewBag.Title = "Index";
}
<h2>Corporate Card Transactions</h2>
@(Html.Kendo().Grid<intranetMVC.Models.CorpCardTransaction>()>
.Name("gvTransactions")    
.Columns(columns => 
{
    columns.Bound(c => c.ID);
    columns.Bound(c => c.AccountID);
    columns.Bound(c => c.CardHolderName);
    columns.Bound(c => c.StatementDate).Format("{0:MM/dd/yyyy}");
    columns.Bound(c => c.PostDate).Format("{0:MM/dd/yyyy}");
    columns.Bound(c => c.TranDate).Format("{0:MM/dd/yyyy}");
    columns.Bound(c => c.Payee);
    columns.Bound(c => c.Amount);
    columns.Bound(c => c.Description);
    columns.Bound(c => c.GL_Account);
    columns.Bound(c => c.BranchCode);
    columns.Bound(c => c.Receipt);
})
    .ToolBar(toolBar => 
    {
        toolBar.Save();                      
    })        
    .Editable(editable => editable.Mode(GridEditMode.InCell))
    .DataSource(dataSource => dataSource
        .Ajax()
        .Batch(true)
        .Events(events => events.Error("error_handler"))            
        .Model(model =>
        {
            model.Id(c => c.ID);
            model.Field(c => c.AccountID).Editable(false);
            model.Field(c => c.CardHolderName).Editable(false);
            model.Field(c => c.StatementDate).Editable(false);
            model.Field(c => c.PostDate).Editable(false);
            model.Field(c => c.TranDate).Editable(false);
            model.Field(c => c.Payee).Editable(false);
            model.Field(c => c.Amount).Editable(false);
        })
          .Read("Transaction_Read", "CorpCardTransactions")
          .Update("Transaction_Update", "CorpCardTransactions")            
    )
)
<script type="text/javascript">
function error_handler(e) {
    if (e.errors) {
        var message = "Errors:'n";
        $.each(e.errors, function (key, value) {
            if ('errors' in value) {
                $.each(value.errors, function() {
                    message += this + "'n";
                });
            }
        });
        alert(message);
    }
}

我在视图中的此处是否正确绑定了网格?

我已经用谷歌搜索了尽可能多的不同方式,但还没有找到我想要做的事情的答案。我认为我的更新功能不起作用,因为网格最初没有与Json结果绑定。不知道如何将我的Linq-to-EF查询作为Json返回到网格。在那之后,似乎应该有一种更简单的方法来进行批量更新。

使用Linq将剑道网格绑定到MVC 5中的EF查询

[HttpGet]
    public ActionResult Transaction_Read([DataSourceRequest] DataSourceRequest request, string AccountID, DateTime StatementDate)
    {
        //var loginName = System.Security.Principal.WindowsIdentity.GetCurrent().Name.Split('''');
        //var username = loginName.Last() + "@xxxx.com";
        var username = "xxxx@xxxx.com";
        var stmtDate = StatementDate;
        var q = from b in db.CorpCardTransactions
                where b.Username == username && b.StatementDate == StatementDate && b.AccountID == AccountID && !b.SubmitDate.HasValue
                select b;            
        return Json(q.ToList().ToDataSourceResult(request));
    }

对于更新,请检查if (ModelState.IsValid) { .... } 是否有任何错误

将您的uysing (db)块替换为以下代码(我没有测试此代码)

using (db)
            {
                foreach (var transaction in corpCardTransaction)
                {
                    var entity = new CorpCardTransaction
                    {
                        ID = transaction.ID,
                        Description = transaction.Description,
                        GL_Account = transaction.GL_Account,
                        BranchCode = transaction.BranchCode,
                        Receipt = transaction.Receipt
                    };
                    db.CorpCardTransactions.Add(entity);
                    db.SaveChanges();
                }
            }