I am looking for a way to send a table of data from view to action in .net core mvc
. There are tones of explanations about sending data from action to a view using razor foreach
and for
loops but how to do the opposite using model binding?
I know/used ajax to send data of this sort but data binding is much easier to implement. Also due to lack of answers that I have found in few hours of searching I am starting to believe that I am missing something. I probably did not understand a basic concept of data binding.
Lets say I have a simple model like so:
public class myMode
{
public string item1 { get; set; }
public string item2 { get; set; }
}
Then the view model will be:
public class MyViewModel
{
public List<myMode> tableData { get; set; }
}
In the view I can use something like:
<table>
<tr>
<th>Item1</th>
<th>Item2</th>
</tr>
foreach (var d in Model.tableData)
{
<tr>
<td>@d.item1</td>
<td>@d.item2</td>
</tr>
}
</table>
This is how to get the data from view model to the table. How to do the opposite?
Lets say that in the same example the user is adding rows to the table. How can we bind the table rows to view model List<myMode> tableData { get; set; }
when form is submited?
CodePudding user response:
<form asp-action="Privacy">
<table>
<tr>
<th>Item1</th>
<th>Item2</th>
</tr>
@{ int i = 0;}
@foreach (var d in Model.tableData)
{
<tr>
<td><input asp-for="@Model.tableData[i].item1" value="@d.item1"/></td>
<td><input asp-for="@Model.tableData[i].item2" value="@d.item2"/></td>
</tr>
@(i )
}
</table>
<input type="submit" />
</form>
CodePudding user response:
How can we bind the table rows to view model List tableData { get; set; } when form is submited?
We can use name="tableData[@i].item1"
to bind the table rows to view model List tableData
They generate the html like :
You can try the below code:
@model MyViewModel
<form asp-action="Index">
<table>
<tr>
<th>Item1</th>
<th>Item2</th>
</tr>
@{
int i = 0;
}
@foreach (var d in Model.tableData)
{
<tr>
<td><input name="tableData[@i].item1" /></td>
<td><input name="tableData[@i].item2" /></td>
</tr> @(i )
}
</table>
<input type="submit" />
</form>
Controller:
[HttpPost]
public IActionResult Index(MyViewModel MyViewModel)
{
return View(MyViewModel);
}
If you want to show the data at the table, then submit it, you can try:
<tr>
<td><input asp-for="@Model.tableData[i].item1" /></td>
<td><input asp-for="@Model.tableData[i].item2" /></td>
</tr>