【问题标题】:Pass checkboxes to controller asp.net mvc将复选框传递给控制器​​ asp.net mvc
【发布时间】:2012-12-31 21:42:22
【问题描述】:

我有一些图像,每个图像旁边都有一个复选框,如下所示:

<input type="checkbox" name="select" value="<%=item.Id%>" />

现在我想通过单击超链接将选定的复选框发送到控制器。我有:

<a href='<%: Url.Action("DeleteSelected", "Product", new { @ShopID = ViewBag.shopIDempty } ) %>'>Delete</a>

在控制器中:

public ActionResult DeleteSelected(int[] select, int ShopID)
    {

        foreach (int checkBoxSelected in select)
        {
            //Do something...               
        }
        return RedirectToAction("Index");
    }

但是没有任何东西传递给 int[] select 并且它始终为 null。怎么了?

【问题讨论】:

  • 如果你想通过链接将参数传递给 DeleteSelected,你必须手动将选中的复选框值添加到链接参数中,否则你应该用表单包装复选框并使用按钮单击 POST 选中的项目

标签: asp.net-mvc checkbox


【解决方案1】:

试试这个:

[HttpPost]
public ActionResult DeleteSelected(FormCollection collection)
{
    try
    {
        string[] test = collection.GetValues("select");
    }
    catch (Exception ex)
    {
        return null;
    }
}

我确实想指出,您采用的方法需要一个表单来包装所有复选框,或者您需要专门构建一个对象以发送到控制器,如 Syed 所示。如果您采用表单方法,您将需要使用链接来触发表单提交或将链接转换为提交按钮并为 ShopID 设置一个隐藏字段。

【讨论】:

    【解决方案2】:

    做这些==> 1) 创建一个包含选中复选框值的数组

    var delete= new Array();
    
         $('.checkboxed').live('click', function () {
                    if ($(this)[0].checked == true) {
                        var itemdel= $(this).val();
                        delete.push(itemdel);
                    } else {
                        var remve =  $(this).val();
                        for (var i = 0; i < delete.length; i++) {
                            if (delete[i] == remve) {
                                delete.splice(i, 1);
                                break;
                            }
                        }
    
                    }
                });
    

    2)点击超链接进行ajax调用

    $.ajax({
                    type: 'POST',
                    contentType: 'application/json; charset=utf-8',
                    url: '/Product/DeleteSelected'
    + '?ShopID =' + ShopIdValue,
                    dataType: 'json',
                    data: $.toJSON(delete),
    
    
                    success: function (result) {
                      window.location.href=result;
                    },
    
    
                    async: false,
                    cache: false
                });
    

    3) 像这样进行操作

    public ActionResult DeleteSelected(int[] select)
    {
    var shopid= Request["ShopID "];
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-29
      • 2019-08-09
      • 2010-09-14
      • 2011-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-15
      相关资源
      最近更新 更多