简体   繁体   English

如何获取MVC5中复选框的选中项的值?

[英]How to get the values of the checked items of checkboxes in MVC5?

I have a view model which includes an ICollection field, something like this: 我有一个包含ICollection字段的视图模型,如下所示:

public class BusinessViewModel
{
    ...

    public virtual ICollection<Subcategory> Subcategories { get; set; }

    ...
}

Then, in my actual view, I have a code segment like this: 然后,在我的实际视图中,我有一个如下代码段:

<div class="form-group">
    @Html.LabelFor(model => model.Subcategories, "Subcategory", htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        <span id="subcats">

        </span>
    </div>
</div>

Afterwards, I have an AJAX call in JS, which simply populates my subcats span field with checkbox items, and my AJAX call looks like this: 之后,我在JS中进行了AJAX调用,该调用仅用复选框项目填充了subcat的span字段,而我的AJAX调用如下所示:

$("#CategoryID").change(function () {
    $("#subcats").empty();

    $.ajax({
        type: 'POST',
        url: '/Account/GetSubcategories',
        dataType: 'json',
        data: { id: $("#CategoryID").val() },
        success: function (subcategories) {
            $.each(subcategories, function (i, subcategory) {
                $("#subcats").append('<input type="checkbox" name="' + subcategory.value + '" value="' + subcategory.id + '" />' + subcategory.value + '<br />');
            });
        },
        error: function (ex) {
            console.log('Failed to retrieve subcategories! ' + ex);
        }
    });

    return false;
});

The point is that, it works all fine in the view, but when I check the items I wish and press the button in order to submit the form, I get an error message saying that a NullReferenceException occurred, when I reach the foreach statement of the below code in my controller: 关键是,它在视图中一切正常,但是当我检查希望的项目并按下按钮以提交表单时,我收到一条错误消息,指出当我到达foreach语句时,发生了NullReferenceException。我的控制器中的以下代码:

    public async Task<ActionResult> RegisterBusiness(BusinessViewModel model)
    {
        if (ModelState.IsValid)
        {
            ...

            foreach (var subcategory in model.Subcategories)
            {
                db.Entry(subcategory).State = EntityState.Unchanged;
                user.Subcategories.Add(subcategory);
            }

            ...
        }
        ...
     }

I guess this is due to the fact I don't assign the selected checkboxes to my model. 我猜这是由于我没有将选定的复选框分配给我的模型。 Can someone, tell me how can I do it in my current setup? 有人可以告诉我如何在当前设置中进行操作吗? A code example where this is achieved would be highly welcomed. 一个实现此目标的代码示例将受到高度欢迎。

EDIT: This is how my subcategory model looks like, at least important part of it: 编辑:这是我的子类别模型的样子,至少是其中的重要部分:

public class Subcategory
{
    public int SubcategoryID { get; set; }
    public string SubcategoryName { get; set; }
}

And also according to the answer below my view now includes this: 而且根据下面的答案,我的观点现在包括:

<div class="form-group">
    @Html.LabelFor(model => model.Subcategories, "Subcategory", htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.ListBoxFor(model => model.SelectedSubcategories, Model.SubcategoryList)
    </div>
</div>

I get a NullReference error again in the ListBoxFor part. 我在ListBoxFor部分中再次收到NullReference错误。

Your SubCategories are null because you are not posting back an values relating to SubCategories . 您的SubCategories为空,因为您没有回发与SubCategories相关的值。 The following example is based on using a multi-select list to choose the sub categories (unchecked checkboxes do not post back, so using checkboxes is much more difficult) 以下示例基于使用多选列表来选择子类别(未选中的复选框不会回发,因此使用复选框要困难得多)

First create a property in you view model that binds to the selected sub categories. 首先,在视图模型中创建绑定到所选子类别的属性。 You may also want a SelectList property to render the initial sub categories to display 您可能还希望SelectList属性呈现要显示的初始子类别

public int[] SelectedSubCategories { get; set; }
public SelectList SubCategoryList { get; set; }

and in the view, render the select 然后在视图中渲染选择

@Html.ListBoxFor(m => m.SelectedSubCategories, Model.SubCategoryList)

then modify your script 然后修改您的脚本

$("#CategoryID").change(function () {
  $("#SelectedSubCategories").empty();
  var url = '@Url.Action("GetSubcategories", "Account")';
  $.get(url, { id: $("#CategoryID").val() }, function(subcategories) {
    $.each(subcategories, function (i, subcategory) {
      var option = $('<option></option>');
      option.val(subcategory.id);
      option.text(subcategory.value);
      $("#SelectedSubCategories").append(option);
    });
  });
});

When posting back, the value of SelectedSubCategories now contains the ID's of each selected sub category 回发时, SelectedSubCategories的值现在包含每个选定子类别的ID

public async Task<ActionResult> RegisterBusiness(BusinessViewModel model)
{
  foreach (int ID in model.SelectedSubCategories)
  {

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM