asp.net-mvc 在MVC中获取多个选定的复选框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17037446/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 02:56:21  来源:igfitidea点击:

Get Multiple Selected checkboxes in MVC

asp.net-mvcasp.net-mvc-4

提问by DharaPPatel

i have a ProductController which is consists of Create method.

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

My Model :

我的型号:

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>();
    }
}

Create Get Method :

创建获取方法:

    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);
    }

this colors i want to fill in the list of checkboxes in which i can select multiple checkboxes.its working properly.

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

Create Post :

创建帖子:

    [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 ??    
    }

Create View :

创建视图:

       @model CrescentAdmin.Models.ProductEntry

code to fill list of checkboxes :

填充复选框列表的代码:

         <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>

i have tried this code , but no luck !!

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

required to fetch which checkboxes are selected ?? Please help

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

采纳答案by karaxuna

Try this:

尝试这个:

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

回答by chamara

I normally use below approach when dealing with checkboxes check whether it helps you.

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

Model:

模型:

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; }
    }
}

Controller:

控制器:

Load CheckBox Value:

加载复选框值:

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);
   }

View:

看法:

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

Now your view shold have list of checkboxes. Now saving CheckBox values to the database.

现在您的视图拥有复选框列表。现在将 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();
        }
    }

Now you have below kind of string in your database

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

safety,power,access

安全、电源、访问

Now fetch the selected values and display the 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);
        }

View:

看法:

  @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>
        }

Let me know if this does not help you.

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

回答by Rahul Sharma

Me too was having a scenario like you and I implemented it using EditorFor by referring this link "ASP.NET MVC - Multiple checkboxes for row selection in HTML table"

我也被有像你这样的场景,我把它用EditorFor参照这个链接来实现“ ASP.NET MVC -在HTML表格多复选框行选择

For that you need create a EditorTemplate folder and need to add the view with a same name of model. View code like below

为此,您需要创建一个 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>

Model can be like below.

模型可以如下所示。

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; }
}

And in parent view you can write html like below

在父视图中,您可以编写如下所示的 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>
.........

Above link has sample project too. I know answer of this question is already accepted but just sharing this. It may help someone. Thanks :-)

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

回答by sakthi sudhan

<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>

回答by Roger Far

I use this extension:

我使用这个扩展:

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());
}