我试图将模型列表传递给控制器,但是没有运气。我在生成空视图,然后将值从填充的表单传递到控制器时遇到问题。我所拥有的:
模型
public class PostsModel
{
[Required]
[DataType(DataType.DateTime)]
public DateTime PublishDate { get; set; }
[Required]
public List<PostModel> Posts { get; set; }
}
public class PostModel
{
public string Language {get;set;}
public string X {get;set;}
public string Y {get;set;}
// and other properties
}
控制器
public IActionResult New()
{
ViewData["ButtonName"] = "Add";
return View(new PostsModel { PublishDate = DateTime.UtcNow });
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> New(PostsModel model)
{
if (ModelState.IsValid)
{
// some code
// never reaches this point
}
return View(model);
}
表格:
<form method="post">
<h4>XYZ</h4>
<hr />
@{
Model.Posts = new List<PostModel>(2);
for (var i = 0; i < 2; i++)
{
Model.Posts.Add(new PostModel());
}
foreach (var test in Model.Posts)
{
<h4>xyz</h4>
<div class="form-group">
<label asp-for="@test.Subject">Temat</label>
<input asp-for="@test.Subject" class="form-control" />
<span asp-validation-for="@test.Subject" class="text-danger"></span>
</div>
}
}
<button type="submit" class="btn btn-primary">@ViewData["ButtonName"]</button>
</form>
当然,模型永远无效。我不知道如何执行此类功能。
答案 0 :(得分:0)
正如@StephenMuecke所说,使用for循环是可行的方法。在我遇到的这个特殊问题中,就足够了:
控制器:
https://
查看:
public IActionResult New()
{
ViewData["ButtonName"] = "Add";
// example:
return View(new PostsModel { PublishDate = DateTime.UtcNow, Posts = new List<PostModel>(2) { new PostModel(), new PostModel() } });
}
我还要感谢M. Kostrzewski和M. Kaletka,他们也帮助我加入了一些.net小组