简体   繁体   中英

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. 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.

$('.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.

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#?

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.

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. 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. Obviously, we would have that wrapped in a loop to ensure it grabs all of the elements with the correlating Grid Id .

Now we would build our 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 . Microsoft actually recommends Newtonsoft.Net over their's, but I will show you the Microsoft one.

Before we deserialize, we need our 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.

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. Hopefully this helps you out a bit though.

you can do it by ajax:

in your aspx.cs file add 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:

$.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?

Get a look at this approach: ASP.NET - Adding an UpdatePanel trigger to a LinkButton inside a gridview

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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