在MVC中获取多个选中的复选框

时间:2013-06-11 06:01:43

标签: asp.net-mvc asp.net-mvc-4

我有一个ProductController,它由Create方法组成。

我的模特:

public class ProductEntry
{
    public Crescent.LinqModel.Product Products { get; set; }
    public ProductSKU SKUs { get; set; }
    public List<SelectListItem> pColors { get; set; }

    public ProductEntry()
    {
        pColors = new List<SelectListItem>();
    }
}

创建获取方法:

    public ActionResult Create()
    {
        CrescentAdmin.Models.ProductEntry product = new CrescentAdmin.Models.ProductEntry();
        var colors = _appData.GetProductColors().ToList();
        for (int i = 0; i < colors.Count; i++)
        {
            if (i == 0)
                product.pColors.Add(new SelectListItem { Value = colors[i].Name.ToString(), Text = colors[i].Name, Selected = true });
            else
                product.pColors.Add(new SelectListItem { Value = colors[i].Name.ToString(), Text = colors[i].Name });
        }

        return View(product);
    }

这种颜色我想填写复选框列表,我可以在其中选择多个复选框。工作正常。

创建帖子:

    [HttpPost]
    [ValidateInput(false)]
    public ActionResult Create(CrescentAdmin.Models.ProductEntry entry, HttpPostedFileBase uploadFile)
    {
      //code to insert in two table
      // required to fetch which checkboxes are selected ??    
    }

创建视图:

       @model CrescentAdmin.Models.ProductEntry

填写复选框列表的代码:

         <tr>
            <td>
                Product Colors
            </td>
            <td>
                @if (Model.pColors != null && Model.pColors.Count > 0)
                {
                    for (int i = 0; i < Model.pColors.Count; i++)
                    {
                        //if (Model.pColors[i])
                        //{
                            <input type="checkbox" value="@Model.pColors[i].Value" id="@Model.pColors[i].Value"/> @Model.pColors[i].Text <br />
                             @Html.HiddenFor(m => Model.pColors[i].Value);
                             @Html.HiddenFor(m => Model.pColors[i].Text);
                             @Html.HiddenFor(m => Model.pColors[i].Selected);
                        //}
                        //else
                        //{
                        //    <input type="checkbox" value="@Model.pColors[i].Value" /> @Model.productColors[i].Name <br />
                        //}
                    }
                }


                @Html.ValidationMessageFor(model => model.SKUs.ProductColors)
            </td>
        </tr>

我试过这段代码,但没有运气!!

需要获取哪些复选框被选中?请帮忙

5 个答案:

答案 0 :(得分:18)

我在处理复选框时通常使用以下方法检查它是否对您有所帮助。

<强>型号:

namespace GateApplication.Models
{
    public class Gate
    {
        public string PreprationRequired { get; set; }
        public List<CheckBoxes>  lstPreprationRequired{ get; set; }
        public string[] CategoryIds { get; set; }
    }

    public class CheckBoxes
    {
        public int ID { get; set; }
        public string Value { get; set; }
        public string Text { get; set; }
        public bool Checked { get; set; }
    }
}

<强>控制器:

加载CheckBox值:

public ActionResult Create()
   {
      List<CheckBoxes> lstchk = new List<CheckBoxes>()
            {
                new CheckBoxes {Text="coduit", Value="coduit" },
                new CheckBoxes {Text="safety", Value="safety" },
                new CheckBoxes {Text="power", Value="power" },
                new CheckBoxes {Text="access", Value="access" }
            };

          var model = new Gate
            {
               lstPreprationRequired=lstchk
            };

            return View(model);
   }

查看:

@foreach (var item in Model.lstPreprationRequired)
    {
        <input type="checkbox" id="@item.Value" name="CategoryIds" value="@item.Text"/>
                  <label for="optionId">@item.Text</label>
       <br />
    }

现在您的视图显示了复选框列表。现在将CheckBox值保存到数据库中。

    [HttpPost]
    public ActionResult Create(FormCollection collection)
    {
        try
        {

            Gate gate = new Gate();
            TryUpdateModel(gate);

            if (ModelState.IsValid)
            {
                gate.PreprationRequired = Request.Form["CategoryIds"];// here you'll get a string containing a list of checked values of the checkbox list separated by commas

                if (string.IsNullOrEmpty(gate.PreprationRequired))//this is used when no checkbox is checked
                    gate.PreprationRequired = "None,None";

                Save();//Save to database
                return RedirectToAction("Index");
            }
            else
            {
                return View();
            }

        }
        catch
        {
            return View();
        }
    }

现在,您的数据库中有以下类型的字符串

  

安全,功率,接入

现在获取所选值并显示视图。

public ActionResult Edit(int id)
        {
           List<CheckBoxes> lstchk = new List<CheckBoxes>()
            {
                new CheckBoxes {Text="coduit", Value="coduit" },
                new CheckBoxes {Text="safety", Value="safety" },
                new CheckBoxes {Text="power", Value="power" },
                new CheckBoxes {Text="access", Value="access" }
             };

            var model = new Gate
            {
                lstPreprationRequired =lstchk,
                CategoryIds = "safety,power,access".Split(',')//here get your comma separated list from database and assign it to the CategoryIds string array, i have used sample text for the values
            };

            return View(model);
        }

查看:

  @foreach (var item in Model.lstPreprationRequired)
        {
             <input type="checkbox" id="@item.Value" name="CategoryIds" value="@item.Text" 
             @foreach (var c in Model.CategoryIds)
             {
               if(c == item.Value)
               {
                  <text> checked="checked"</text>
               }
             }/>
             <label for="optionId">@item.Text></label>
        }

如果这对您没有帮助,请告诉我。

答案 1 :(得分:7)

试试这个:

@Html.HiddenFor(m => Model.pColors[i].Value);
@Html.HiddenFor(m => Model.pColors[i].Text);
@Html.CheckBoxFor(m => Model.pColors[i].Selected);

答案 2 :(得分:1)

我也有像你这样的场景,我使用EditorFor通过引用此链接“ASP.NET MVC - Multiple checkboxes for row selection in HTML table

来实现它。

为此您需要创建一个EditorTemplate文件夹,并且需要添加具有相同名称模型的视图。查看以下代码

@model EditorForSample.Models.ProductViewModel


<tr>
  <td class="text-nowrap">@Html.CheckBoxFor(m => m.Selected, new {@class="chkSelect"})  </td>
<td colspan="3">
    @Model.Name
    @Html.HiddenFor(m => m.Name)
</td>
<td>
    @Model.Price
    @Html.HiddenFor(m => m.Price)
</td>

模型可以如下所示。

public class ProductPageViewModel
{
    public string Message { get; set; }

    public List<ProductViewModel> ProductsList { get; set; }
}

public class ProductViewModel
{
    public bool Selected{ get; set; }
    public string Name { get; set; }
    public int Price { get; set; }
}

在父视图中,您可以编写如下的HTML

 .......
  <div class="col-md-12">
        <table class="table table-bordered table-striped">
            <thead>
                <tr>
                    <th><input type="checkbox" id="chkSelectAll" /></th>
                    <th colspan="3">
                        Product Name
                    </th>
                    <th>
                        Cost
                    </th>

                </tr>
            </thead>
            <tbody>
                @Html.EditorFor(m => m.ProductsList)
            </tbody>
        </table>
    </div>
.........

以上链接也有示例项目。我知道这个问题的答案已被接受但只是分享这个。它可能会帮助某人。谢谢: - )

答案 3 :(得分:1)

<script>
   $("#btndownloading").click(function (e) {
                var ckebox_value = $("input[name=cmmdLabels]:checked").map(function () {
                    if ($(this).val() != 0) {
                        return $(this).val();
                    }
                }).get();
                var ckeck_box_length = ckebox_value.length;
                if (ckeck_box_length != 0) {
                    $.ajax({
                        url: '@Url.Action("dowloadingfile", "dowloading")',
                        type: "POST",
                        data: JSON.stringify({ selectionvalue_ck: ckebox_value }),
                        contentType: "application/json; charset=utf-8",
                        success: function (data) {

                        }, 
                        }
                    });
                }
                else {
                    alert("Please select at least one File");
                }
            });
</script>

 [HttpPost]
        public ActionResult dowloadingfile(string[] selectionvalue_ck)
        {
			string fileName = "";
			for (int j = 0; j < selectionvalue.Length; j++)
                {
					fileName = selectionvalue_ck[j];
				}
		}
<input class="cb-element" name="cmmdLabels" value="1.txt" type="checkbox">
<input class="cb-element" name="cmmdLabels" value="2.txt" type="checkbox">
<input class="cb-element" name="cmmdLabels" value="3.txt" type="checkbox">
<input class="cb-element" name="cmmdLabels" value="4.txt" type="checkbox">
<input class="cb-element" name="cmmdLabels" value="5.txt" type="checkbox">

<button id="btndownloading">Download file</button>

答案 4 :(得分:0)

我使用此扩展程序:

public static MvcHtmlString CheckBoxListFor<TModel, TProperty>(
    this HtmlHelper<TModel> htmlHelper,
    Expression<Func<TModel, IEnumerable<TProperty>>> expression,
    IEnumerable<SelectListItem> multiSelectList,
    Object htmlAttributes = null)
{
    // Derive property name for checkbox name
    var body = expression.Body as MemberExpression;
    if (body == null)
        return null;

    String propertyName = body.Member.Name;

    // Get currently select values from the ViewData model
    IEnumerable<TProperty> list = expression.Compile().Invoke(htmlHelper.ViewData.Model);

    // Convert selected value list to a List<String> for easy manipulation
    var selectedValues = new List<String>();

    if (list != null)
        selectedValues = new List<TProperty>(list).ConvertAll(i => i.ToString());

    // Create div
    var ulTag = new TagBuilder("ul");
    ulTag.AddCssClass("checkBoxList");
    ulTag.MergeAttributes(new RouteValueDictionary(htmlAttributes), true);

    // Add checkboxes
    foreach (var item in multiSelectList)
    {
        ulTag.InnerHtml += String.Format(
            "<li><input type=\"checkbox\" name=\"{0}\" id=\"{0}_{1}\" value=\"{1}\" {2} /><label for=\"{0}_{1}\">{3}</label></li>",
            propertyName,
            item.Value,
            selectedValues.Contains(item.Value) ? "checked=\"checked\"" : "",
            item.Text);
    }

    return MvcHtmlString.Create(ulTag.ToString());
}