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

Dha*_*tel 9 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>();
    }
}
Run Code Online (Sandbox Code Playgroud)

创建获取方法:

    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);
    }
Run Code Online (Sandbox Code Playgroud)

这个颜色我想填写复选框列表,我可以选择多个复选框.工作正常.

创建帖子:

    [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 ??    
    }
Run Code Online (Sandbox Code Playgroud)

创建视图:

       @model CrescentAdmin.Models.ProductEntry
Run Code Online (Sandbox Code Playgroud)

用于填写复选框列表的代码:

         <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>
Run Code Online (Sandbox Code Playgroud)

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

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

cha*_*ara 19

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

模型:

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; }
    }
}
Run Code Online (Sandbox Code Playgroud)

控制器:

加载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);
   }
Run Code Online (Sandbox Code Playgroud)

视图:

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

现在您的视图显示了复选框列表.现在将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();
        }
    }
Run Code Online (Sandbox Code Playgroud)

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

安全,通电,通路

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

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);
        }
Run Code Online (Sandbox Code Playgroud)

视图:

  @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>
        }
Run Code Online (Sandbox Code Playgroud)

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


kar*_*una 7

试试这个:

@Html.HiddenFor(m => Model.pColors[i].Value);
@Html.HiddenFor(m => Model.pColors[i].Text);
@Html.CheckBoxFor(m => Model.pColors[i].Selected);
Run Code Online (Sandbox Code Playgroud)