简体   繁体   中英

ASP.NET MVC ADO.NET Query per table row

Here I have this table:

表样本图片

If I click the button, I want to pass the table per row to the controller, then perform ADO.NET Query per row, like for example, perform "UPDATE tbluser SET note='INACTIVE' WHERE id=@id" per row.

One of the main purpose of this is when i filter the table, only the visible rows will be passed.

I already have a code here to pass to controller using AJAX but I don't know what to do afterwards.

JS:

var HTMLtbl =
{
    getData: function (table) {
        var data = [];
        oTable.rows({ search: 'applied' }).every(function () {
            var cols = [];
            var rowNode = this.node();
            $(rowNode).find("td").each(function () {
                cols.push($(this).text().trim() || null);
            });
            data.push(cols);
        });
        return data;
    }
}


$("btnSubmit").on("click", function () {
    var data = HTMLtbl.getData($(".datatable"));
    var parameters = {};
    parameters.array = data;

    var request = $.ajax({
        async: true,
        cache: false,
        dataType: "json",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/Home/SubmitTable",
        data: JSON.stringify(parameters),
        success: function () {
            window.location.href = "/Home/Index";
        }
    });

    request.fail(function (jqXHR, textStatus) {
        alert("Request failed: " + textStatus);
    });
});

Controller:

[HttpPost]
public JsonResult SubmitTable(string[][] array)
{
    //I don't know what to do here now, please help 
}

My Solution based on Mostafa's answer:

JS:

var HTMLtbl =
{
    getData: function () {
        var data = [];
        oTable.rows({ search: 'applied' }).every(function () {
            var cols = [];
            var rowNode = this.node();
            $(rowNode).find("td").each(function () {
                cols.push($(this).text().trim() || null);
            });
            data.push(cols);
        });
        return data;
    }
}

$("#btnSubmit").on("click", function () {
    var data = HTMLtbl.getData($(".datatable"));
    var parameters = {};
    parameters.array = data;

    var request = $.ajax({
        async: true,
        cache: false,
        dataType: "json",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/Home/SubmitTable",
        data: JSON.stringify(parameters),
        success: function () {
            window.location.href = "/Home/Index";
        }
    });

    request.fail(function (jqXHR, textStatus) {
        alert("Request failed: " + textStatus);
    });
});

Controller:

[HttpPost]
    public JsonResult SubmitTable(string[][] array)
    {
        string result = string.Empty;
        try
        {
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
            con.Open();
            foreach (var arr in array)
            {
                SqlCommand cmd = new SqlCommand("UPDATE tbluser SET remark='INACTIVE' WHERE id = @id", con);
                cmd.Parameters.AddWithValue("@id", arr[0]);
                cmd.ExecuteNonQuery();
            }
            con.Close();
        }
        catch (Exception ex)
        {
            result = ex.Message;
        }
        return Json("Records updated successfully.", JsonRequestBehavior.AllowGet);
    }

I can now use this for more complicated stuff, thanks

If you want to update a custom row you can add a button for each row with custom text and icon, then add a "data-" attribute to this button and path your row id,

<input type="button" data-rowId="1" class="changeActivationState">activate</input>

in this example I added a data field to my imput after that I define this javascript method:

  $(".changeActivationState").click(function(){
    $(this).data("rowId")//get the selected row id and call you service 
  });

using this code you can read first element for each row and perform a web service call for all rows

  var arr = [];
  $("#yourtable tr").each(function(){
      arr.push($(this).find("td:first").text()); //put elements into array
  });

and using this code you can read all rows into a json object

 var tbl = $('#yourtable tr').map(function() {
    return $(this).find('td').map(function() {
    return $(this).html();
   }).get();
 }).get();

assume that you passed the list to action

  int[] passedIDsfromBrowser = ///filled with data that comes from browser;
  SqlConnection connection = ....
  SqlCommand command = new SqlCommand(connection);
  command.CommandText = "Update MYTABLENAME Set Active = true where ID in (" string.Join(",", passedIDsfromBrowser ) + ")";
   connection.Open();
   command.ExecuteNonQuery();
   connection.Close();

this is a pseudo code. or if you want a loop and updating each row with a loop

  SqlConnection connection = ....
  SqlCommand command = new SqlCommand(connection);
  connection.Open();
  for(int i = 0 ; i < passedIDsfromBrowser.Length; i++){
     command.CommandText = "YOURQUERY";
     command.ExecuteNonQuery();
  }
  connection.Close();

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