【问题标题】:After adding a row in a CRUD in grid telerik, updating or deleting button are not working在网格 Telerik 的 CRUD 中添加一行后,更新或删除按钮不起作用
【发布时间】:2019-12-31 01:52:42
【问题描述】:

我有一个带有存储过程的 CRUD,我需要使用剑道网格来处理它。控制器和添加、编辑和删除按钮工作正常,但是在我的 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);
        }

我调用存储过程的类:

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"))
        )
)

我的存储过程和我的表:

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  

【问题讨论】:

  • 非常完整且易于理解的问题,做得好!作为起点,您应该在所有 CRUD 操作中返回一个 DataSourceResult,请参见本示例中的控制器:demos.telerik.com/aspnet-mvc/grid/editing-popup 您是否在浏览器的控制台中收到任何消息?
  • @CarstenFranke 非常感谢您的回复,但它不起作用,因为我正在为 ClientDB 使用“公共 int”,并且它是调用存储过程所必需的,如果我尝试添加 DataSourceResult* 它会生成错误:“”int”不包含“DataSourceResult”的定义,并且最佳扩展方法重载 'QueryableExtensions.ToDataSourceResult (DataTable, DataSourceRequest)' 需要接收类型为“DataTable”的“
  • 然后将其包装成一个数组:return Json(new[] { cliDB.Update(t_Client) }.ToDataSourceResult(request, ModelState)); 如果Update 或任何其他操作返回int,您应该考虑检索更新的对象并将其返回。否则网格无法与您返回的内容正常工作。查看来自 Kendo 的示例,他们发送的内容和收到的内容,看看他们是如何做到的。顺便提一句。对于非 GET 请求,您可以删除 JsonRequestBehavior.AllowGet
  • @CarstenFranke 如果我将它返回到一个数组中,它仍然不起作用,如果我尝试将它作为一个对象发送,就像我做的那样,它不起作用而且我没有知道要做什么。你能告诉我如何发送吗?请。

标签: asp.net-mvc kendo-ui grid telerik crud


【解决方案1】:

我已经找出问题所在,它只需要一个重新加载网格的函数。我更改的内容在 .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);
        }

【讨论】:

    【解决方案2】:

    好的,所以从你的问题中我可以理解的是,一旦你添加了一个新项目,系统就会继续在 add 模式下使用新项目。

    通过查看您似乎从未重置/设置您正在添加的新项目的 id 的代码,因此网格和数据源将假定您正在添加并随后返回的项目是基于的新项目default id,它在构造新项目时给出。

    您需要做的就是将 id 重新生成为新的 guid,然后将该结果保存到服务器,然后以新的 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”的地方
    • 是的,我在发表评论后看到了网格。这就是我删除它的原因。那么当您检查创建过程的结果时返回了什么?
    • 当我创建行时,我将调试放在它正常创建并正确放置答案,但是,正如我所说,当我单击更新或删除按钮时,它会进入控制器 ClientCreate 和在 ClientDB 中进入 Add
    • 我对从 http 响应返回到网格的内容更感兴趣。因此,如果您查看浏览器网络响应会有所帮助。
    【解决方案3】:

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

    Grid Create ActionResult 方法应该返回带有新生成的 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) 方法应该返回新创建的对象而不是int

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

    【讨论】:

      猜你喜欢
      • 2015-03-13
      • 1970-01-01
      • 1970-01-01
      • 2015-07-24
      • 2012-06-09
      • 1970-01-01
      • 2021-03-12
      • 2017-05-16
      • 1970-01-01
      相关资源
      最近更新 更多