I am trying to bind an input of list items to a List
object but it seems that the only way this can be done is if I initialized my List
with a certain number of those objects and then bind the properties from the input to the null properties of the objects in my List
So for example, the following will give out of bounds exception unless I add some PersonInputModel
objects to PersonInput
Index ViewPage
@page
@model IndexModel
@{
ViewData["Title"] = "Home page";
}
<div >
<form method="post">
<label for="name">Name</label>
<input type="text" asp-for="PersonInput[0].Name" />
<label for="age">Age</label>
<input type="number" asp-for="PersonInput[0].Age" />
</form>
</div>
Index PageModel
public class IndexModel : PageModel
{
private readonly ILogger<IndexModel> _logger;
[BindProperty]
public IList<PersonInputModel> PersonInput { get; set; } = new List<PersonInputModel>();
public IndexModel(ILogger<IndexModel> logger)
{
_logger = logger;
}
public void OnGet()
{
}
}
PersonInputModel
public class PersonInputModel
{
public string Name { get; set; }
public int Age { get; set; }
public Person ToPerson()
{
return new Person
{
Name = Name,
Age = Age
};
}
}
But what if the user can add more input forms to add more than one person ? What if the user feeds more input than the number of objects in PersonInput
list ? How can I make my input list dynamic ?
CodePudding user response:
Below is a work demo , you can refer to it.
Person.cs
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
PersonInputModel
public class PersonInputModel
{
public string Name { get; set; }
public int Age { get; set; }
public List<Person> Persons { get; set; }
}
IndexModel
public class IndexModel : PageModel
{
private readonly ILogger<IndexModel> _logger;
[BindProperty]
public PersonInputModel PersonInputModel { get; set; }
public IndexModel(ILogger<IndexModel> logger)
{
_logger = logger;
}
public void OnGet()
{
}
[HttpPost]
public void OnPost(PersonInputModel personInputModel)
{
}
}
Index.cshtml
@page
@model IndexModel
@{
ViewData["Title"] = "Home page";
}
<form method="post">
<label for="name">Name</label>
<input type="text" asp-for="PersonInputModel.Name" />
<label for="age">Age</label>
<input type="number" asp-for="PersonInputModel.Age" />
<button type="button" onclick="myfunction()">Add Person</button>
<table id="myTable" style="display: none;" >
<tr>
<th>Name</th>
<th>age</th>
</tr>
</table>
<div >
<div >
<button type="submit" >Create</button>
</div>
</div>
</form>
<script type="text/javascript">
var mytab = document.getElementById("myTable");
var i = 0;
function myfunction() {
document.getElementById("myTable").style.display = "block";
document.getElementById("myTable").insertRow(-1).innerHTML =
'<td> <input type="text" name="PersonInputModel.Persons[' i '].Name" /> </td><td> <input type="number" name="PersonInputModel.Persons[' i '].Age" /> </td>';
i ;
}
</script>
Result: