Here is the Model:
public class TestModel
{
public string Data { get; set; }
public List<string> Datas { get; set; }
}
Here is the view:
@model InventoryWeb.Models.TestModel
@using (Html.BeginForm())
{
@Html.DisplayFor(modelItem => Model.Data)
@Html.HiddenFor(m => m.Data)
<table class="table">
<tr>
<th>
Data
</th>
<th></th>
</tr>
@for (int i = 0; i < Model.Datas.Count; i++)
{
@Html.Hidden("Datas["+ i + "]", Model.Datas[i])
<tr>
<td>
@Html.DisplayFor(modelItem => Model.Datas[i])
</td>
<td>
<input type="submit" value="Submit" formaction="SubmitTest" formmethod="post"/>
</td>
</tr>
}
</table>
}
How to pass the selected row number (the number of row on which user pressed the "Submit" button) to controller? TempData/Viewbag/whatever it is possible to use to pass this info to Controller site when Submitting.
The way you wrote it, it will send all the data back to server for any row.
You can insert a form in each row:
@model InventoryWeb.Models.TestModel
@Html.DisplayFor(modelItem => Model.Data)
<table class="table">
<tr>
<th>
Data
</th>
<th></th>
</tr>
@for (int i = 0; i < Model.Datas.Count; i++)
{
<tr>
<td>
@Html.DisplayFor(modelItem => Model.Datas[i])
</td>
<td>
@using (Html.BeginForm())
{
@Html.Hidden("rowNumber", i)
<input type="submit" value="Submit" formaction="SubmitTest" formmethod="post"/>
}
</td>
</tr>
}
</table>
But I prefer using javascript in this situations.
Edit
With JavaScript:
@using (Html.BeginForm("SubmitTest"))
{
@Html.DisplayFor(modelItem => Model.Data)
@Html.HiddenFor(m => m.Data)
<input type="hidden" id="rowNumber" name="rowNumber" />
<table class="table">
<tr>
<th>
Data
</th>
<th></th>
</tr>
@for (int i = 0; i < Model.Datas.Count; i++)
{
@Html.Hidden("Datas["+ i + "]", Model.Datas[i])
<tr>
<td>
@Html.DisplayFor(modelItem => Model.Datas[i])
</td>
<td>
<input type="button" value="Submit" onclick="SubmitForm(@i, this);"/>
</td>
</tr>
}
</table>
}
<script>
function SubmitForm(i, btn){
$("#rowNumber").val(i);
var form = $(btn).closest("form");
form.submit();
}
</script>