0

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.

8
  • Are you trying to generate grid table dynamically based on user inputs ? Commented Dec 1, 2017 at 9:53
  • 1
    You need to write two loops, one for the rows and one for columns and you can render the x number of trs and y number tds inside that. Commented Dec 1, 2017 at 9:55
  • @stom will you please see the jsfiddle.net/EKfut/2 . i want to pass the table data to the .net mvc controller as arrray . Commented Dec 6, 2017 at 5:27
  • Your first question title was grid-view on basis of input rows and coloums and i answered that question, now you have changed the question title and this not advisable , if you are new to SO check this before asking :) Commented Dec 6, 2017 at 9:41
  • ok sir , i will go through it Commented Dec 6, 2017 at 10:02

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.