Vikram Yadav
Vikram Yadav

Reputation: 27

How to generate and post html table Grid data to mvc controller as array

If I input data to the table I want to get the data as array in mvc controller. I want to pass input values of each row and column to controller as an array. so i can perform various operations on array

function createTable()
{
    document.getElementById('tb_container').innerHTML = "";
    var rows = document.getElementById('tb_rows').value;
    var cols = document.getElementById('tb_cols').value;

    tblHtml = '<table>'
    for (i = 0; i < rows; i += 1)
    {
        tblHtml += '<tr>';
        for (j = 0; j < cols; j += 1)
        {
            tblHtml += '<td><input type="text"></td>';
        }
        tblHtml += '</tr>';
    }
    tblHtml += '</table>';
    document.getElementById('tb_container').innerHTML = tblHtml;
}



td {
    min-width: 100px;
    min-height: 20px;
    border: solid 1px #000;
}




<ul>
    <li>
        Rows:
        <input type="text" id="tb_rows">
    </li>
    <li>
        Columns :
        <input type="text" id="tb_cols">
    </li>
    <li>
        <input type="button" value="Create Table" onclick="createTable()">
    </li>
</ul>

<div id="tb_container"></div>

please suggest me how should i pass the input data (i.e values in rows and columns) from user as array.

Upvotes: 0

Views: 2107

Answers (1)

Shaiju T
Shaiju T

Reputation: 6607

This should work to generate rows and columns from user input and post those grid data to mvc action method:

Grid View Models:

public class GridVM
{
    public GridVM()
    {
        GridData = new List<GridData>();
    }
    public int NoOfRows { get; set; }

    public int NoOfColumns { get; set; }

    public List<GridData> GridData { get; set; }
}


public class GridData
{
    public string CellData { get; set; }

    public int NoOfRows { get; set; }

    public int NoOfColumns { get; set; }
}

Grid Get Index Action Method:

public ActionResult Index()
 {

   return View();
 }

Grid Get Index View:

@model Demo.Models.GridVM

<style>
table td {
    border: 1px solid black;
}
</style>


<label>No Of Rows</label>

@Html.TextBoxFor(m => m.NoOfRows)

<br />

<label>No Of Columns</label>

@Html.TextBoxFor(m => m.NoOfColumns)

<button type="button" id="addGrid">Add Grid</button>

<br />

@using (Html.BeginForm("SaveGridData", "Home", FormMethod.Post))
{
<table id="gridData">

@Html.Partial("_AddGridPartials", new Demo.Models.GridData())

</table>

<br />

<input type="submit" value="Submit Grid Data"/>

}

Add Grid Action Method:

[HttpPost]
public PartialViewResult AddGrid(GridVM addGrid)
 {

  var gridData = new GridData();

  gridData.NoOfRows = addGrid.NoOfRows;
  gridData.NoOfColumns = addGrid.NoOfColumns;

  return PartialView("_AddGridPartials", gridData);

  }

Add Grid Partial View:

Note: Install BeginCollectionItem HtmlHelper from here to have unique name attributes in form to bind to your model properties.

@model Demo.Models.GridData
@using HtmlHelpers.BeginCollectionItem


@for (var i = 0; i < Model.NoOfRows; i++)
{


<tr>

@for (var j = 0; j < Model.NoOfColumns; j++)
{
 using (Html.BeginCollectionItem("gridData"))
  {
    <td>
     @Html.TextBoxFor(model => model.CellData)
    </td>
  }
}

</tr>

<br />

}

Save Grid Data Action Method:

[HttpPost]
public ActionResult SaveGridData(GridVM gridDetails)
 {

  var gridDataArray = gridDetails.GridData.ToArray();

  // Or you can loop through the list save using you repository

  foreach (var data in gridDetails.GridData)
    {
      var cellValue = data.CellData;

      // TODO save cellValue using your repository

    }

  return Json(new { Message = "Done!, All Details Saved" },JsonRequestBehavior.AllowGet);

  }

Add Grid Script:

   <script>

   $(document).ready(function () {

    var gridDetails = $('#gridData');
    $('#addGrid').click(function () {

        var gridObject = new Object();
        gridObject.NoOfRows = $("#NoOfRows").val();
        gridObject.NoOfColumns = $("#NoOfColumns").val();


        $.ajax({
            url: '@Url.Action("AddGrid", "Home")',
            type: "POST",
            cache: false,
            data: JSON.stringify({ addGrid: gridObject }),
            contentType: "application/json; charset=utf-8",
            success: function(data) {
                if (data) {
                    gridDetails.append(data);
                }
            },
            error: function(jqXhr, textStatus, errorThrown) {
                alert(errorThrown);
            }
        });
    })

    });

   </script>

Upvotes: 1

Related Questions