在网格 telerik 的 CRUD 中添加一行后,更新或删除按钮不起作用

After adding a row in a CRUD in grid telerik, updating or deleting button are not working

我有一个带有存储过程的 CRUD,我需要使用 kendo 网格。控制器和添加、编辑和删除按钮工作正常,但在我的 CRUD 中添加一行后,这些按钮(添加除外)不起作用。我的意思是,在我添加之后,所有按钮都开始只是添加,即使我按下编辑或删除按钮,我也不知道出了什么问题。

我的控制器:


        private Entities db = new Entities();

        ClientDB cliDB = new ClientDB();

        // GET: Client
        public ActionResult ClientIndex()
        {
            return View("ClientIndex");
        }

        public ActionResult ClientRead([DataSourceRequest]DataSourceRequest request)
        {
            return Json(cliDB.ListAll().ToDataSourceResult(request));

        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult ClientCreate([DataSourceRequest]DataSourceRequest request, t_Client t_Client)
         {
            return Json(cliDB.Add(t_Client), JsonRequestBehavior.AllowGet);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult ClientUpdate([DataSourceRequest]DataSourceRequest request, t_Client t_Client)
        {
            return Json(cliDB.Update(t_Client), JsonRequestBehavior.AllowGet);
        }

        public ActionResult ClientDelete([DataSourceRequest] DataSourceRequest request, string c_Id)
        {
            Guid g = Guid.Parse(c_Id);
            return Json(cliDB.Delete(g), JsonRequestBehavior.AllowGet);
        }

我调用存储过程的class:

public class ClientDB
    {
        private SqlConnection con;

        private void connection()
        {
            string cs = ConfigurationManager.ConnectionStrings["Entities"].ConnectionString;
            con = new SqlConnection(cs);

        }

        public List<t_Client> ListAll()
        {
            connection();
            List<t_Client> lst = new List<t_Client>();
            SqlCommand com = new SqlCommand("SP_SelectClient", con);
            com.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter da = new SqlDataAdapter(com);
            DataTable dt = new DataTable();
            con.Open();
            da.Fill(dt);
            con.Close();
            lst = (from DataRow rdr in dt.Rows
                   select new t_Client()
                   {
                       c_Id = (Guid)rdr["c_Id"],
                       c_Name = rdr["c_Name"].ToString(),
                       c_NoClients = rdr["c_NoClients"].ToString(),
                       c_DocType = rdr["c_DocType"].ToString(),
                       c_DocNumber = rdr["c_DocNumber"].ToString(),
                       c_TaxpayerType = rdr["c_TaxpayerType"].ToString(),
                       c_DianClassification = rdr["c_DianClassification"].ToString(),
                       c_Address = rdr["c_Address"].ToString(),
                       c_AddrType = rdr["c_AddrType"].ToString(),
                       c_Telephone = rdr["c_Telephone"].ToString(),
                       c_BusinessName = rdr["c_BusinessName"].ToString()
                   }).ToList();

            return lst;
        }


        public int Add(t_Client client)
        {
            connection();
            SqlCommand com = new SqlCommand("SP_InsertUpdateClient", con);
            com.CommandType = CommandType.StoredProcedure;
            com.Parameters.AddWithValue("@c_Id", client.c_Id);
            com.Parameters.AddWithValue("@c_NoClients", client.c_NoClients);
            com.Parameters.AddWithValue("@c_Name", client.c_Name);
            com.Parameters.AddWithValue("@c_DocType", client.c_DocType);
            com.Parameters.AddWithValue("@c_DocNumber", client.c_DocNumber);
            com.Parameters.AddWithValue("@c_TaxpayerType", client.c_TaxpayerType);
            com.Parameters.AddWithValue("@c_DianClassification", client.c_DianClassification);
            com.Parameters.AddWithValue("@c_Address", client.c_Address);
            com.Parameters.AddWithValue("@c_AddrType", client.c_AddrType);
            com.Parameters.AddWithValue("@c_Telephone", client.c_Telephone);
            com.Parameters.AddWithValue("@c_BusinessName", client.c_BusinessName);
            com.Parameters.AddWithValue("@Action", "Insert");
            int i;
            con.Open();
            i = com.ExecuteNonQuery();
            con.Close();

            return i;
        }

        public int Update(t_Client client)
        {
            connection();
            int i;
            SqlCommand com = new SqlCommand("SP_InsertUpdateClient", con);

            com.CommandType = CommandType.StoredProcedure;
            com.Parameters.AddWithValue("@c_Id", client.c_Id);
            com.Parameters.AddWithValue("@c_NoClients", client.c_NoClients);
            com.Parameters.AddWithValue("@c_Name", client.c_Name);
            com.Parameters.AddWithValue("@c_DocType", client.c_DocType);
            com.Parameters.AddWithValue("@c_DocNumber", client.c_DocNumber);
            com.Parameters.AddWithValue("@c_TaxpayerType", client.c_TaxpayerType);
            com.Parameters.AddWithValue("@c_DianClassification", client.c_DianClassification);
            com.Parameters.AddWithValue("@c_Address", client.c_Address);
            com.Parameters.AddWithValue("@c_AddrType", client.c_AddrType);
            com.Parameters.AddWithValue("@c_Telephone", client.c_Telephone);
            com.Parameters.AddWithValue("@c_BusinessName", client.c_BusinessName);
            com.Parameters.AddWithValue("@Action", "Update");
            con.Open();
            i = com.ExecuteNonQuery();
            con.Close();
            return i;
        }

        public int Delete(Guid c_Id)
        {
            connection();
            int i;
            SqlCommand com = new SqlCommand("SP_DeleteClient", con);
            com.CommandType = CommandType.StoredProcedure;
            com.Parameters.AddWithValue("@c_Id", c_Id);
            con.Open();
            i = com.ExecuteNonQuery();
            con.Close();
            return i;
        }

    }

cshtml

@(Html.Kendo().Grid<CRUD5.Models.t_Client>()
        .Name("grid")
        .HtmlAttributes(new { style = "height:500px; height:800px:" })
        .Columns(columns =>
        {
            columns.Bound(c => c.c_NoClients).Title("Clients").Width("auto");
            columns.Bound(c => c.c_Name).Title("Name");
            columns.Bound(c => c.c_DocType).Title("Doc Type");
            columns.Bound(c => c.c_DocNumber).Title("Doc Number");
            columns.Bound(c => c.c_TaxpayerType).Title("Taxpayer Type");
            columns.Bound(c => c.c_DianClassification).Title("Dian Classification");
            columns.Bound(c => c.c_Address).Title("Address");
            columns.Bound(c => c.c_AddrType).Title("AddrType");
            columns.Bound(c => c.c_Telephone).Title("Telephone");
            columns.Bound(c => c.c_BusinessName).Title("Business Name");
            columns.Command(command => { command.Edit(); command.Destroy(); }).Width(200);
        })
        .ToolBar(toolbar =>
        {
            toolbar.Create();
        })
        .Editable(editable => editable.Mode(GridEditMode.PopUp))
        .Scrollable()
        .Sortable()
        .Pageable(pageable => pageable
            .Refresh(true)
            .PageSizes(true)
            .ButtonCount(5))
        .DataSource(dataSource => dataSource
            .Ajax()
            .Model(model => model.Id(p => p.c_Id))
            .Read(read => read.Action("ClientRead", "Client"))
            .Create(create => create.Action("ClientCreate", "Client"))
            .Update(update => update.Action("ClientUpdate", "Client"))
            .Destroy(destroy => destroy.Action("ClientDelete", "Client"))
        )
)

我的存储过程和我的 table:

CREATE TABLE t_Client(
 c_Id   UNIQUEIDENTIFIER  PRIMARY KEY    DEFAULT NEWID(),
 c_NoClients NVARCHAR(100) NULL, 
 c_Name NVARCHAR(100) NULL, 
 c_DocType NVARCHAR(100) NULL, 
 c_DocNumber NVARCHAR(100) NULL, 
 c_TaxpayerType NVARCHAR(100) NULL, 
 c_DianClassification NVARCHAR(100) NULL, 
 c_Address NVARCHAR(100) NULL, 
 c_AddrType NVARCHAR(100) NULL, 
 c_Telephone NVARCHAR(100) NULL, 
 c_BusinessName NVARCHAR(100) NULL,
 c_Action NVARCHAR(10) NULL,
 c_Estate NVARCHAR(6) NULL,
 ValidFrom DATETIME2 GENERATED ALWAYS AS ROW START,
 ValidTill DATETIME2 GENERATED ALWAYS AS ROW END,
 PERIOD FOR SYSTEM_TIME (ValidFrom, ValidTill)
)
WITH
(
    SYSTEM_VERSIONING = ON
    (
        HISTORY_TABLE = dbo.t_ClientHistory,
        HISTORY_RETENTION_PERIOD = 10 YEARS
    )
 )
GO

-------------------------------------------------------------------------------------
--Insert and Update Client 

Create Procedure SP_InsertUpdateClient    
(    
 @c_Id uniqueidentifier,
 @c_NoClients NVARCHAR(100),
 @c_Name NVARCHAR(100),
 @c_DocType NVARCHAR(100),
 @c_DocNumber NVARCHAR(100),
 @c_TaxpayerType NVARCHAR(100),
 @c_DianClassification NVARCHAR(100),
 @c_Address NVARCHAR(100),
 @c_AddrType NVARCHAR(100),
 @c_Telephone NVARCHAR(100),
 @c_BusinessName NVARCHAR(100),
 @Action varchar(10)    

)    
As    
Begin    
if @Action='Insert'    
Begin    
insert into t_Client(c_NoClients, c_Name, c_DocType, c_DocNumber, c_TaxpayerType, c_DianClassification , c_Address , c_AddrType , c_Telephone , c_BusinessName ) 
        values (@c_NoClients,  @c_Name,  @c_DocType,  @c_DocNumber,  @c_TaxpayerType,  @c_DianClassification ,  @c_Address ,  @c_AddrType ,  @c_Telephone ,  @c_BusinessName   )
End    
if @Action='Update'    
Begin    
update t_Client set 
     c_NoClients = @c_NoClients,
     c_Name = @c_Name,
     c_DocType = @c_DocType,
     c_DocNumber = @c_DocNumber,
     c_TaxpayerType = @c_TaxpayerType,
     c_DianClassification = @c_DianClassification,
     c_Address = @c_Address,
     c_AddrType = @c_AddrType,
     c_Telephone = @c_Telephone,
     c_BusinessName = @c_BusinessName
     where c_Id = @c_Id    ;    
End  
End


-------------------------------------------------------------------------------------
--Delete Employee  

Create Procedure SP_DeleteClient  
(    
@c_Id uniqueidentifier
)    
as     
Begin    
if exists (select * from t_Client  where c_Id = @c_Id )
update t_Client  set c_Estate = 'false' where c_Id = @c_Id;
update t_Client set c_Action = 'Delete' where c_Id = @c_Id;
End  

好的,据我从你的问题中了解到的是,一旦你添加了一个新项目,系统就会继续以 add 模式处理新项目。

通过查看代码,您似乎从未 resetting/setting 您要添加的新项目的 ID,因此网格和数据源将假定您要添加的项目,随后 returning 是一个新项目,它基于它在构造新项目时给出的 default id。

您需要做的就是将 id 重新生成为新的 guid,然后将该结果保存到服务器,然后 return 使用新的 guid 作为 id 的新创建的对象,例如:

     [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult ClientCreate([DataSourceRequest]DataSourceRequest request, t_Client t_Client)
         {
             t_Client.c_Id = Guid.NewGuid();
             cliDB.Add(t_Client); 
            return Json(new[] {t_Client}.DataSourceResult(request, ModelState), JsonRequestBehavior.AllowGet);
        }

我已经弄清楚是什么问题了,它只需要一个重新加载网格的函数。我更改的内容在 .cshtml 中。

在 .DataSource 中,我添加了调用函数 "onRequestEnd"

的 .Events
.DataSource(dataSource => dataSource
                    .Ajax()
                    .Model(model => model.Id(p => p.c_Id))
                    .Read(read => read.Action("ClientRead", "Client"))
                    .Create(create => create.Action("ClientCreate", "Client"))
                    .Update(update => update.Action("ClientUpdate", "Client"))
                    .Destroy(destroy => destroy.Action("ClientDelete", "Client"))
                    .Events(events =>
                    {
                        events.RequestEnd("onRequestEnd");
                    })
                    )

这是函数:

<script>

    function onRequestEnd(event) {
        console.log(event.type);
        if (event.type == "update" || event.type == "create" || event.type == "destroy") {
            $("#grid").data("kendoGrid").dataSource.read();  
        }
    }

</script>

除此之外,我还纠正了@CarstenFranke 推荐我的一些内容,所以最终的控制器是:

private Entities db = new Entities();

        ClientDB cliDB = new ClientDB();

        // GET: Client
        public ActionResult ClientIndex()
        {
            return View("ClientIndex");
        }

        public ActionResult ClientRead([DataSourceRequest]DataSourceRequest request)
        {
            return Json(cliDB.ListAll().ToDataSourceResult(request));

        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult ClientCreate([DataSourceRequest]DataSourceRequest request, t_Client t_Client)
        {
            return Json(new[] { cliDB.Add(t_Client) }.ToDataSourceResult(request, ModelState), JsonRequestBehavior.AllowGet);     
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult ClientUpdate([DataSourceRequest]DataSourceRequest request, t_Client t_Client)
        {
            return Json(new[] { cliDB.Update(t_Client) }.ToDataSourceResult(request, ModelState), JsonRequestBehavior.AllowGet);
        }

        public ActionResult ClientDelete([DataSourceRequest] DataSourceRequest request, string c_Id)
        {
            Guid g = Guid.Parse(c_Id);
            return Json(new[] { cliDB.Delete(g) }.ToDataSourceResult(request, ModelState), JsonRequestBehavior.AllowGet);
        }

创建新记录后重新加载网格不是一个好习惯。它会解决问题,但会增加您访问数据库获取数据的次数,因为您将在每次添加过程后重新加载网格,即使是失败的过程也是如此。

Grid Create ActionResult 方法应该return 新创建的对象具有新生成的 ID PrimaryKey。所以你应该将你的 ClientCreate 更新成这样:

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult ClientCreate([DataSourceRequest]DataSourceRequest request, t_Client t_Client)
    {
        return Json(new[] { cliDB.Add(t_Client)}.ToTreeDataSourceResult(request, ModelState));
    }

cliDB.Add(t_Client)方法应该return新创建的对象不是int

您可以在此处查看 telerik 的文档和演示 https://demos.telerik.com/aspnet-mvc/grid/editing-inline