Search code examples
javascript.netajax

how to convert html table content to an array and send it to controller?


I have converted a html table content in a array but unable to send it to the controller. Pls help

  • I have tried a lot of references but every time the parameter in controller getting null values
function sendtabledata() {
var element = document.getElementById("pveloandata");
var rows = element.querySelectorAll("tr");


var jsarray = [];

            rows.forEach((r, i) => {
                if (i > 0) {
                    const tabledata = {}
                    const rowitems = r.children
    
                    tabledata["srl"] = i;
                    tabledata["date"] = rowitems[1].textContent;
                    tabledata["balance"] = rowitems[2].textContent;
                    tabledata["intbal"] = rowitems[3].textContent;
    
                    jsarray.push(tabledata);
                }
            })
        
        jsarray = JSON.stringify({ 'jsarray': jsarray });
    
            $.ajax({
                
                ContentType: 'application/json; charset=utf-8',
                dataType: "json",
                type: "POST",
                traditional:true,
                url: '@Url.Action("gettabledata", "Loan")',
                data: jsarray,
               
                success: function (data) {
                   
    
                },
                error: function (err) {
                    alert(err);
                }
            });
    
        }

//controller Method

 public ActionResult gettabledata(string[] jsarray)
        {

           
            return View();
        }

Solution

  • I can see issue with your post method below

    jsarray = JSON.stringify({ 'jsarray': jsarray });
    

    here you are sending

    {"jsarray":[...]} instead of [...]
    

    but you are accepting jsarray[] from server side

    you need to update your from front end side like

    jsarray = JSON.stringify(jsarray); //this will send array of element
    

    on server side you can use like

    public ActionResult gettabledata([FromBody]string[] jsarray)