简体   繁体   English

您如何跟踪ASP.NET中的复选框更改?

[英]How do you keep track of checkbox changes in ASP.NET?

I have a Gridview with many rows, and each row has two checkboxes, one for US availability, and another for UK availability. 我有一个包含很多行的Gridview,每行有两个复选框,一个用于美国可用性,另一个用于英国可用性。 Before, the code made it so that on every checkbox change, the page would do a postback, and code to update for that item would be run. 在此之前,代码已经做到这一点,以便在每个复选框更改时,页面都会进行回发,并且将运行针对该项目进行更新的代码。 As you can imagine, for hundreds of rows, any major changes will take a very long time and it becomes extremely tedious through this method. 可以想象,对于几百行而言,任何重大更改都将花费很长时间,并且通过这种方法变得非常乏味。

So I created some jQuery listeners for changes on a checkbox, and these methods essentially add the index of the clicked checkbox to existing Javascript arrays based on what changes were made to that checkbox since the creation of the page. 因此,我为复选框上的更改创建了一些jQuery侦听器,这些方法实质上是根据自页面创建以来对该复选框所做的更改,将单击的复选框的索引添加到现有Javascript数组中。

$('.checkUs input:checkbox').click(function () {
    var row = $(this).parent().parent().parent().index();
    var isChecked = $(this).is(':checked');

    if (isChecked && $.inArray(row, usRowsChecked) === -1 && $.inArray(row, usRowsUnchecked) === -1)
      usRowsChecked.push(row);
    else if (isChecked && $.inArray(row, usRowsUnchecked) !== -1)
      usRowsUnchecked.splice($.inArray(row, usRowsUnchecked), 1);

    if (!isChecked && $.inArray(row, usRowsUnchecked) === -1 && $.inArray(row, usRowsChecked) === -1)
      usRowsUnchecked.push(row);
    else if (!isChecked && $.inArray(row, usRowsChecked) !== -1)
      usRowsChecked.splice($.inArray(row, usRowsChecked), 1);
  });

Now I don't know how to get this information back to the server to run the SQL queries, and from researching it for a little bit, I'm not so sure this is the best solution. 现在,我不知道如何将这些信息返回到服务器以运行SQL查询,并且从一点研究来看,我不确定这是否是最佳解决方案。

Upon the user clicking the "Save" button, I need to send four arrays to the back-end: 用户单击“保存”按钮后,我需要将四个阵列发送到后端:

var usRowsChecked = [];
var usRowsUnchecked = [];
var ukRowsChecked = [];
var ukRowsUnchecked = [];

How do I communicate this information to the code-behind in C#? 如何将此信息传达给C#中的代码背后?

Your question though simple, could have some architecture or spaghetti consequences if you don't rethink and reevaluate after I provide the approach to send that data to code behind. 您的问题尽管很简单,但是如果您在我提供了将数据发送到背后的代码之后不进行重新思考和重新评估的话,可能会导致体系结构或意大利面条的后果。 You would use Ajax, this would allow you to build a model or object to send to code behind. 您将使用Ajax,这将允许您构建模型或对象以发送到后面的代码。

function BuildModel (Id, Country) {
     var content = {
          Id : Id,
          Country : Country
     };

     return content;
}

For brevity sake, there isn't any null checks which should be done. 为了简洁起见,没有任何应该执行的null检查。 This will build a simple object for us to pass back. 这将为我们建立一个简单的对象以传递回去。

var content = new Array();
content.Push(BuildModel($('.Id'), $('.Country));

Those two lines are quite simple, we build an Array and begin populating it. 这两行非常简单,我们构建一个Array并开始填充它。 Obviously, we would have that wrapped in a loop to ensure it grabs all of the elements with the correlating Grid Id . 显然,我们会将其包裹在一个循环中,以确保它使用相关的Grid Id捕获所有元素。

Now we would build our Ajax: 现在我们将构建我们的Ajax:

var jsonObject = JSON.stringify(content);

$.ajax({
     url: '<%= Page.ResolveURL("~/SomePage.aspx") %>',
     data: { Model : jsonObject },
     type: 'POST'

     success: function () {
         // Do something with returned data.
     }
});

Then on code behind you could use the built in .Net JavaScript.Serializer or Newtonsoft.Net . 然后,在后面的代码中,您可以使用内置的.Net JavaScript.SerializerNewtonsoft.Net Microsoft actually recommends Newtonsoft.Net over their's, but I will show you the Microsoft one. 实际上,Microsoft推荐Newtonsoft.Net ,但我将向您展示Microsoft。

Before we deserialize, we need our Model . 在反序列化之前,我们需要Model

public class Example
{
     public int Id { get; set; }
     public bool Country { get; set; }
}

We have our model, so when we deserialize we would do the following: 我们有模型,因此在反序列化时,将执行以下操作:

var model = new Example();
var serializer = new JavaScriptSerializer();
List<Example> deserialize = serializer.Deserialize<List<Example>>(Request["Model"]);

Now you have a workable collection of all of that data. 现在,您拥有了所有这些数据的可行集合。

The above approach isn't the only way though, if your applications warrants PostBacks you could use the built control UpdatePanel or runat="server" to grab elements from front-end in code behind. 但是,上述方法并不是唯一的方法,如果您的应用程序需要PostBacks ,则可以使用内置控件UpdatePanelrunat="server"从后端代码中的前端获取元素。

You have several choices, but the proper choice will vary on your application. 您有多种选择,但是正确的选择会因您的应用程序而异。 Each has a perk and a drawback, but either way your fighting the Asp.Net Page Life Cycle. 每个都有一个特权和一个缺点,但是无论如何,您都将与Asp.Net Page生命周期作战。 Hopefully this helps you out a bit though. 希望这对您有所帮助。

you can do it by ajax: 你可以通过ajax做到这一点:

in your aspx.cs file add WebMethod: 在您的aspx.cs文件中添加WebMethod:

    [WebMethod]
    public static int SaveArray(int[] usRowsChecked,int[] usRowsUnchecked, int[]ukRowsChecked, int[] ukRowsUnchecked )
    {
        //do here whatever you want with values
    }

in your aspx file (javascript) add method like below: 在您的aspx文件(javascript)中添加如下方法:

$.ajax({
    type: 'POST',
    data: "{usRowsChecked:" + usRowsChecked + 
    ", usRowsUnchecked :" + usRowsUnchecked +
    ", ukRowsChecked :" + ukRowsChecked +
    ", ukRowsUnchecked :" + ukRowsUnchecked +"}",
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    async: true,
    url: "YourPage.aspx/SaveArray",
    success: function (result) {
        alert("success");
    },
    error: function (msg) {
        alert("error");
    }
});

Why don't you insert the Grid into an UpdatePanel and use Commands? 为什么不将Grid插入UpdatePanel并使用Commands?

Get a look at this approach: ASP.NET - Adding an UpdatePanel trigger to a LinkButton inside a gridview 让我们看一下这种方法: ASP.NET-将UpdatePanel触发器添加到gridview内的LinkBut​​ton上

You can use CommandName and CommandArgument (in your case row-id) like this: Check box inside repeater , How to get command name value in the check changed function 您可以像下面这样使用CommandName和CommandArgument(在您的情况下为row-id): Repeater内的复选框,如何在选中更改的函数中获取命令名称值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM