如何使用jquery ajax显示复选框列表中的项目

How to display items from checkbox list using jquery ajax

本文关键字:列表 项目 复选框 显示 何使用 jquery ajax      更新时间:2023-09-26

我正在尝试获取使用ajax和jquery选择的某个复选框的值。现在我已经在我的网站上列出了所有项目,但我想让用户选中复选框来获取所选项目。

控制器:

[HttpGet] public JsonResult getCategoryItems(){}

如何做到这一点?

视图:

@for (int i = 0; i < Model.CarsCount.Count(); i++)
{                
    var cars = Model.CarsCount.ElementAt(i);              
    <span class="label label-info">
        @cars.CategoryName <span class="badge">@cars.CategoryCount</span
    </span>
    @Html.CheckBox(cars.CategoryName, cars.isChecked, new { id = "carsCheckbox"})
}

正如您所看到的,上面的代码只是计算要作为复选框列出的类别中的项目。不过,我只想让用户选中复选框,这样用户就可以通过从复选框中选中项目来获得项目。

private IEnumerable<CarViewModel> GetListOfCars()
    {
        var listOfcars = this.Data.cars.All()
            .Select(t => new CarViewModel
            {
                Id = t.Id,
                Title = t.Title,
                Price = t.Price ,
                FileName = t.FileName
            });
        return listOfcars;
    }

您的问题有点令人困惑。但我假设当用户选择一个复选框时,您希望将该复选框的Id发送到您的操作方法,并获得一些响应,用于更新UI。

正如Stephen Muecke在评论中提到的,您当前的代码正在为复选框生成重复的Id值。表单元素不应该有重复的id。

假设HesViewModel中的每个项目都有一个Id属性(具有唯一值),我们将使用它发送到服务器。

当您呈现checkBox时,您可能会传入用于呈现css类的html属性(我们将用于jQuery选择,以侦听复选框状态的任何更改)和Id(我们将使用此唯一值发送到服务器)

for (int i = 0; i < Model.HesViewModels.Count(); i++)
{
    var cars = Model.HesViewModels.ElementAt(i);
    <span class="label label-info"> @cars.DetailRasonCode </span>
    @Html.CheckBox(cars.CategoryName,
               cars.isChecked, new { @class = "myCheck", id = cars.Id})
}

现在我们将有一些jQuery代码来监听复选框中的更改。当它被选中时,我们将使用Id属性值,并使用ajax将其发送到服务器。

$(function () {
    $("input.myCheck").change(function(e) {
        var _this = $(this);
        if (_this.is(":checked")) {
            var id = _this.attr("id");
            alert(id);
            //Let's make the Ajax call now
            var url = "@Url.Action("getCategoryItems","Home")?id=" + id;
            $.get(url, function () {
            }).done(function (res) {
                alert('response from server received');
                console.log(res);
                //Use the response as needed to update your UI
            }).fail(function () {
                alert("error");
            });
        }
    });
});

当然,现在你的操作方法应该接受一个id作为参数

[HttpGet] 
public JsonResult getCategoryItems(int id)
{
   // to do : Send some useful data back.
   return Json(new { Data :"Good"},JsonRequestBehaviour.AllowGet);
}