【问题标题】:send multiple checkbox vales to controller using ajax in asp.net mvc在 asp.net mvc 中使用 ajax 将多个复选框值发送到控制器
【发布时间】:2018-04-03 17:59:23
【问题描述】:

我已经下载了 Microsoft Music-Store 应用程序,因此我正在对此进行一些更改,所以我要更改的是由 (id、title、genreId、artistid ......) 组成的专辑模型,所以我想使用复选框根据流派ID显示专辑列表,无论我单击列表的复选框应该显示什么,所以我编写了这样的代码。

在这里我有一个小问题,当我转到显示所有流派名称的 GenericList 视图时这意味着什么(在每个流派名称中显示带有复选框的复选框,此复选框未选中)但专辑列表未显示(所有复选框均未选中列表应该显示)当我每次检查一些复选框时,它会准确显示,但未选中专辑的所有复选框列表都没有显示。所以请帮我做些什么更改

控制器:

   `public ActionResult GenericList()
    {
        ViewBag.Generic = db.Genres.ToList();
        return View();
    }`

public ActionResult _GenreList(string cbk)
    {
        var listIds = new List<Int32>(Array.ConvertAll(cbk.Split(','), Convert.ToInt32));
        var list = from a in db.Albums
                   select a;
        if (cbk != null) 
        {
            list = from l in db.Albums
                       where listIds.Contains(l.GenreId)
                       select l;
        }
        else
        {
            list= from a in db.Albums
                  select a;
        }
        return PartialView(list);
    }

操作结果

 <ul id="checkboxFilter">
    @foreach(var item in ViewBag.Generic)
    {
    <li>
        <div class="custom-checkbox">
            <input type="checkbox" class="cbk" id="@item.GenreId.ToString()" /> @item.Name
        </div>
    </li>

    }
</ul>

Javascript

<script>
$(document).ready(function () {
    $('.cbk').change(function () {
        var ID = "";
        $('.cbk').each(function (index, val) {
            if ($(this).is(':checked')) {
                ID += $(val).attr("Id") + ",";
                alert('id Name: ' + ID);
            }
        });
        var data = {};
        data.cbk = ID.slice(0, ID.length - 1);
        if (ID != 0) {
            $.ajax({
                url: '/Home/_GenreList',
                method: 'POST',
                data: data,
                success: function (data) {
                    $("#Generic_list").html(data);
                },
                error: function () {
                    alert("Something went Worng.");
                }
            });
        }
    });
});

【问题讨论】:

  • public ActionResult _GenreList(string[] cbk) { var list = from a in db.Albums select a; if(cbk !=null) { list=list.Where(x =&gt; cbk.Contains(x.Genre.Name)); } else { list = from a in db.Albums select a; } return PartialView(list); }

标签: javascript asp.net-mvc-4


【解决方案1】:

您需要为组中的所有复选框设置相同的名称,例如"name"="genres"

和 value 属性到您要传递给控制器​​的值,例如"value="@item.GenreId.ToString()"

然后在控制器中,您将收到一个流派数组,例如

public ActionResult _GenreList(string[] genres)

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-28
  • 1970-01-01
  • 2015-08-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多