Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
571 views
in Technique[技术] by (71.8m points)

c# - Passing an array of ids from view pages to controller

I discovered that the ids are not getting passed through from the razor page to the controller. So my int[] userIds is empty but I don't know why or how to fix it. Please help.

Below is my code.

Account Controller:

public class AccountController : Controller
{
    private readonly UserManager<ApplicationUser> _userManager;

    private readonly SignInManager<ApplicationUser> _signInManager;

    private readonly RoleManager<Role> _roleManager;

    public AccountController(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, RoleManager<Role> roleManager)
    {
        _userManager = userManager;
        _signInManager = signInManager;
        _roleManager = roleManager;
    }

    public IActionResult Remove()
    {
        var users = _userManager.Users.OrderBy(o=> o.LastName).ToList();
        RemoveViewModel removeViewModel = new RemoveViewModel(users);
        return View(removeViewModel);
    }

    [HttpPost]
    public IActionResult Remove(int[] userIds)
    {

        if (userIds == null || userIds.Length==0)
        { 
            throw new System.ArgumentException("Array is empty", "original");
        }

        return Redirect("/Home/Index");
    }

view:

    @model WebApplication1.ViewModels.RemoveViewModel
<html>
<body>
    <form asp-controller="Account" asp-action="Remove" method="post">

            @foreach (var item in Model.Users)
            {
            <div>
                <label> @item.FirstName @item.LastName</label>
                <input type="checkbox" id="@item.Id" value="@item.Id" />
            </div>
            }


        <input type="submit" value=" Remove User" /><br>

    </form>

    </body>
</html>

ViewModel:

    namespace WebApplication1.ViewModels
{
    public class RemoveViewModel
    {
        public List<ApplicationUser> Users { get; set; }

        public RemoveViewModel(List<ApplicationUser> users)
        {
            Users = users; 
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The model binding in Asp.Net MVC is done by the name attribute of the html elements. So, add the name attribute to the input with the value of userIds. Hence, multiple elements with one name will bind to a single parameter of the same name that results in a list:

<input name="userIds" type="checkbox" id="@item.Id" value="@item.Id" />

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...