在MVC/Razor中,如何获取多个复选框的值并将其全部传递给控制器​​? [英] In MVC/Razor, how do I get the values of multiple checkboxes and pass them all to the controller?

查看:170
本文介绍了在MVC/Razor中,如何获取多个复选框的值并将其全部传递给控制器​​?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个视图,其中包含来自模型的项目列表.我需要为每行添加一个复选框,让用户选择多个复选框,然后将所选行的某些标识符传递给控制器​​.我知道如何通过操作链接传递单个值,但是我不确定如何通过操作链接传递多个值或如何收集"选择了哪些行.我将在下面显示一些代码尝试.有人可以帮我弄清楚为什么我无法获取传递给控制器​​的所有复选框的值吗?

I have a view with a list of items from a model. I need to add a checkbox to each row, have the user select multiple check boxes, and pass some identifier of what row was selected to the controller. I know how to pass a single value through an action link, but I'm not sure how to pass multiple values through an action link or how to "collect" which rows were selected. I'll show some of my code attempts below. Can someone help me sort out why I can't get the values of all the checkboxes passed to the controller?

这是我的页面

Checkbox     App ID     Date     Name
   []          1        5/10     Bob
   []          2        5/10     Ted
   []          3        5/11     Alice

我需要用户执行的操作是选择第1行和第2行; 3(例如),并将那些应用ID传递给控制器​​.

What I need the user to do is select rows 1 & 3 (for example) and have those App ID's passed to the controller.

我开始列出各种尝试,但决定只是显示我当前的尝试,看看是否有人可以指出我做错了什么.我在在线示例和我的示例之间看到的主要区别是,我的示例使用PagedList并在foreach循环中创建表的行.

I started listing various attempts, but decided just to show my current attempt and see if anyone could point out what I'm doing wrong. The main difference I see between examples online and mine is that mine uses a PagedList and creates the rows of the table in a foreach loop.

击中控制器时,参数ints为空白.如何从复选框中获取值?我使用此站点的基本思想是将所有复选框都命名为相同,并通过操作链接传递ICollection: http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx/

The parameter ints is blank when it hits the controller. How do I get the values from the checkboxes into it? I used this site for the basic idea of naming all the checkboxes the same and passing a ICollection through the action link: http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx/

查看:

@model PagedList.IPagedList<CarmelFinancialWeb.Models.ModelMerchantSummary>
<div class="block" style="width: 100%; float: left">
<p class="block-heading"> 
Merchant Application Report
</p>
<div class="table-holder">
    <table class="table" style="margin-bottom: 0px">
            <tbody>
                @foreach (var item in Model)
                {
                    <tr>
                        <td>
                            <input type="checkbox" name="ints" value=item.ApplicationID />
                        </td>
                    <td>
                        @Html.ActionLink(item.ApplicationID.ToString(), "ViewApplication", new { ID = item.ApplicationID, edit = 1 }, new AjaxOptions { HttpMethod = "GET" })
                    </td>
                    <td>
                        @Convert.ToDateTime(item.ApplicationDate).ToString("M/d/yy")
                    </td>
                    <td>
                        @item.ApplicantName
                    </td>
        </tbody>
    </table>
</div>
</div>
@Html.ActionLink("Print Application", "PrintApplication", "CreateContract", new { @class = "btn btn-primary" })

控制器:

    [AuthorizeAdmin]
    public ActionResult PrintApplication(ICollection<int> ints, string ID)
    {
        Contracts_Create contract = new Contracts_Create();
        ModelApplication currentApplication = new ModelApplication();
        currentApplication.contract = new ModelContract();
        return File(contract.CreatePDF_PrintedApplication_English(currentApplication.contract.location, currentApplication.contract), "application/pdf");
    }

这被标记为另一个问题的重复.问题在于是否可以使用非顺序输入名称.我的问题是我使用的不是非顺序输入,但仍然无法正常工作.我理解这个概念,只是想不通为什么我的特定代码无法正常工作.我花了很多时间,找不到适合我特定代码的答案.谢谢!

This got tagged as a duplicate of another question. The question there was about whether non-sequential input names could be used. My problem is that I'm using inputs that are not non-sequential, but it is still not working. I understand the concept, I just can't figure out why my specific code is not working. I've put a lot of time into this and can't find the answer to my specific code. Thanks!

推荐答案

尝试将ViewModel传递到您的页面中,并使用模型绑定器将同一视图模型发布回您的控制器中

Try passing a ViewModel into your page, and using the model binder to post the same view model back into your controller

型号:

public class MerchantModel
{
    public int AppId { get; set; }
    public string Name { get; set; }
    public bool IsSelected { get; set; }
}

public class MerchantViewModel
{
    public List<MerchantModel> Merchants { get; set; }
}

控制器:

public class DefaultController : Controller
{
    // GET: Default
    public ActionResult Index()
    {
        var merchant1 = new MerchantModel
        {
            AppId = 1,
            Name = "Bob"
        };
        var merchant2 = new MerchantModel
        {
            AppId = 2,
            Name = "Ted"
        };
        var merchant3 = new MerchantModel
        {
            AppId = 3,
            Name = "Alice"
        };

        List<MerchantModel> list = new List<MerchantModel>();
        list.Add(merchant1);
        list.Add(merchant2);
        list.Add(merchant3);

        var model = new MerchantViewModel
        {
            Merchants = list
        };

        return View(model);
    }

    [HttpPost]
    public ActionResult Index(MerchantViewModel model)
    {
        return View(model);
    }
}

查看:

 @model TestCheckBoxes.Models.MerchantViewModel

    @{
        Layout = null;
    }

    <!DOCTYPE html>

    <html>
    <head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div> 
        <form action="/default/index" method="post">
            <table>
                @for (int i = 0; i < Model.Merchants.Count; i++)
                {
                    <tr>
                        <td>
                            @Html.CheckBoxFor(x => x.Merchants[i].IsSelected)
                        </td>
                        <td>
                            @Html.HiddenFor(x => x.Merchants[i].AppId)
                            @Model.Merchants[i].AppId
                        </td>
                        <td>
                            @Html.HiddenFor(x => x.Merchants[i].Name)
                            @Model.Merchants[i].Name
                        </td>
                    </tr>
                }
            </table>

            <button type="submit">Submit</button>
        </form>



    </div>
</body>
</html>

在控制器的[HttpPost]方法中,您将具有MerchantModel的列表,其bool值为true或false.这样,您可以检查它是否为真,然后从那里获取AppId.

Back in your [HttpPost] method in your controller, you will have a list of MerchantModel's with the bool value either true or false. This way you can check if it's true and just grab the AppId from there.

这篇关于在MVC/Razor中,如何获取多个复选框的值并将其全部传递给控制器​​?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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