Pass back multiple selected Checkbox Options using Razor in MVC

我们两清 提交于 2021-01-29 15:12:22

问题


I am using ASP.NET MVC to populate a group of checkboxes. These checkboxes change depending on what the user selects on the previous view. I am using Razor. In the view I have:

    @foreach (var skills in Model.SkillsAvailable)
    {
        <input name="pack" type="checkbox" value="@skills" /> @skills<br />
    }

    @Html.HiddenFor(m => m.SkillsSelected, new { @class = "hidden" })

I have a few others that look nearly identical to this but are single selection radio buttons. It functions by jQuery taking the selected option on change and populating the HiddenFor. The HiddenFor is passed to the control upon submit. No issues with that.

But for my checkbox, I'm not sure how to send multiple items back. If this list populates 10 items, and the user can only select 2, how do I add them to List<string> SkillsSelected?

My first instinct is that I can add somehow using another foreach loop (like foreach that is selected, add to a list). But I have no idea what that looks like, and Google searching isn't bringing anything up except for using bools, which makes sense if the list is the same every time, but not if the list has between 5 and 30 options depending on the previous selection.

At this point in time, I don't have any jQuery controlling this section, so I don't have code for it. My controller is populating the list of checkboxes just fine, but not handling anything else.

The only properties in my model that matters are these, and I have no problem changing them in necessary.:

    public List<string> SkillsAvailable { get; set; }
    public List<string> SkillsSelected { get; set; }

回答1:


The trick with lists in views (razor) is to use for loops instead of foreach. With this, your html elements will be treated as arrays. Here an example for your case:

A change in the model, have the SkillsSelected property list as holder of the boolean values

public List<string> SkillsAvailable { get; set; }
public List<bool> SkillsSelected { get; set; }

Then, on the view, use for loop

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    for (int i = 0; i < Model.SkillsAvailable.Count; i++)
    {
        @Html.CheckBoxFor(m => Model.SkillsSelected[i]) @Model.SkillsAvailable[i] <br />
        @Html.HiddenFor(m => Model.SkillsAvailable[i])
    }
    <input type="submit" value="Submit" />
}

And as a reference, here an example on how to pass and receive the model in the controller

public ActionResult Index()
{
    var model = new Model1()
    {
        SkillsAvailable = new List<string>() { "Uno", "Dos", "Tres" }
    };
    return View(model);
}

[HttpPost]
public ActionResult Index(Model1 model)
{
    return View(model);
}


来源:https://stackoverflow.com/questions/57312680/pass-back-multiple-selected-checkbox-options-using-razor-in-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!