将ID数组从视图页面传递到控制器 [英] Passing an array of ids from view pages to controller

查看:72
本文介绍了将ID数组从视图页面传递到控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现ID并没有从剃须刀页面传递到控制器.所以我的int[] userIds为空,但我不知道为什么或如何解决它.请帮忙.

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.

下面是我的代码.

帐户控制器:

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");
    }

视图:

    @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:

ViewModel:

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

        public RemoveViewModel(List<ApplicationUser> users)
        {
            Users = users; 
        }
    }
}

推荐答案

Asp.Net MVC中的模型绑定是通过html元素的name属性完成的.因此,将name属性添加到input,值为userIds.因此,具有一个名称的多个元素将绑定到一个具有相同名称的单个参数,从而产生一个列表:

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" />

这篇关于将ID数组从视图页面传递到控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆