I want to get display the values the user has typed after the "Add" button is pressed. But I don’t know why my code displays undefined instead of the values.
I am passing multiple instances of my model objects to the controller as a list.
This is my View:
@model List<MVCModel.Models.Student>
<b>Result</b> @ViewBag.s <br />
@using (Html.BeginForm("Form", "Home", FormMethod.Post))
{
<table>
<tbody id="GenaratorList">
<tr>
@{
int counter = 0;
<td>Enter Name: </td>
<td>@Html.TextBoxFor(m => m[counter].Name)</td>
<td>Enter Age: </td>
<td>@Html.TextBoxFor(m => m[counter].Age)</td>
<td><input type="button" value="Add" onclick="addGenarator()" /></td>
</tr>
counter++;
}
<tbody>
</table>
<input type="submit" value="Submit Form"/>
}
<script>
count = 0;
function addGenarator() {
var Name = $('#Name').val();
var Age = $('#Age').val();
var Student = "studentModels[" + count + "]";
$('#GenaratorList').append('<tr><td><input id="' + Student + '.Name" Name="' + Student + '.Name" type="text" class="form-control" readonly value="' + Name + '"></td><td><input id="' + Student + '.Age" Age="' + Student + '.Age" type="text" class="form-control" readonly value="' + Age + '"></td></tr>');
$('#Name,#Age').val('');
count++;
}
</script>
2
Answers
You have not assigned id to the textboxfor kindly assign the id
Your Form (HttpPost) API was expected to receive a request body with an array named s. You will pass the array as (name) studentModels based on your JS code.
And you miss out on the name attribute for each Age input.
make sure the array name in View must be matched with the Controller parameter name.
use this script