我正在嘗試將串列項的輸入系結到一個List物件,但似乎可以做到這一點的唯一方法是,如果我List用一定數量的這些物件初始化我,然后將輸入中的屬性系結到的 null 屬性我的物件List
因此,例如,除非我將一些PersonInputModel物件添加到PersonInput
索引視圖頁面
@page
@model IndexModel
@{
ViewData["Title"] = "Home page";
}
<div class="text-center">
<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>
索引頁面模型
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()
{
}
}
人員輸入模型
public class PersonInputModel
{
public string Name { get; set; }
public int Age { get; set; }
public Person ToPerson()
{
return new Person
{
Name = Name,
Age = Age
};
}
}
但是如果用戶可以添加更多的輸入表單來添加多個人呢?如果用戶輸入的輸入比PersonInput串列中的物件數量多怎么辦?如何使我的輸入串列動態化?
uj5u.com熱心網友回復:
下面是一個作業demo,大家可以參考一下。
個人.cs
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
人員輸入模型
public class PersonInputModel
{
public string Name { get; set; }
public int Age { get; set; }
public List<Person> Persons { get; set; }
}
指數模型
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)
{
}
}
索引.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 class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<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>
結果:

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/465585.html
