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>
grid-view on basis of input rows and coloumsand 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 :)