Hi @Nico L ,
> I am still not getting the view model data on submit. It shows "model.count = 0"
It looks like what you are experiencing is a new problem.
I simplified the code you provided for testing and found that it is a Model binding problem.
- For targets that are collections of simple types, model binding looks for matches to parameter_name or property_name. If no match is found, it looks for one of the supported formats without the prefix.
- In other words, you are using foreach to traverse the data, so when you use tag helper, the name of the input in the rendered html cannot be correctly bound to the parameters in the action.
- You can use for loop data. You can refer to the code I tested below.
Model
public class RoleUsersViewModel { public string UserId { get; set; } public string UserName { get; set; } public bool IsSelected { get; set; } }
Controller
public class TestController : Controller
{
public IActionResult Index()
{
List<RoleUsersViewModel> test = new List<RoleUsersViewModel>();
for(int i = 1; i < 10; i++)
{
test.Add(new RoleUsersViewModel
{
UserId = i.ToString(),
UserName = "UserName" + i.ToString(),
IsSelected = true
});
}
var pMd = new StaticPagedList<RoleUsersViewModel>(test, 1, 3, test.Count);
return View(pMd);
}
[HttpPost]
public IActionResult Index(string roleId, IEnumerable<RoleUsersViewModel> model)
{
return View();
}
View
@using X.PagedList.Mvc.Core;
@using X.PagedList;
@model IPagedList<WebApplication24.Models.RoleUsersViewModel>
<form method="post">
<table class="table" border="1">
<tbody>
@for(var i=0;i<Model.Count;i++)
{
<tr>
<td>
<div class="card-body">
<div class="mx-auto col-2">
<div class="form-check m-3 text-nowrap">
<input type="hidden" asp-for="@Model[i].UserId" />
<input type="hidden" asp-for="@Model[i].UserName" />
<input asp-for="@Model[i].IsSelected" class="form-check-input" />
<label class="form-check-label" asp-for="@Model[i].IsSelected">
<b>@Model[i].UserName</b>
</label>
</div>
</div>
<div asp-validation-summary="All" class="text-danger"></div>
</div>
</td>
</tr>
}
</tbody>
</table>
<input type="submit" value="Grant" asp-route-roleId="1" class="btn btn-warning rounded" />
</form>
If the answer is helpful, please click "Accept Answer" and upvote it. Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread. Best Regards, YihuiSun