FormCollection绑定复选框选择与C#MVC中的输入

时间:2017-06-16 10:09:14

标签: c# razor data-binding

我想知道,如果有一种简单的方法可以将我的Checkbox选项与其他值绑定,稍后会将其发送到服务器。

例如下面的图片,如果我在这里选择3个值(Jaan,Kapp,Taavi),则服务器从复选框接收 3 (人)值,但 4 值下拉列表(参见代码后的示例)。

enter image description here

在代码中,这看起来像是(可能不是最佳实践)

<table>
        @for (int i = 0; i <= Model.Persons.Count - 1; i++)
        {
            bool check = true;
            if (Model.Persons[i].TrainingAttendeeId == 0)
            {
                check = false;
            }
            // Gets person training roles list
            var trainingRolesList = (ViewBag.TrainingRoles as SelectList).ToList();
            trainingRolesList.ForEach(p => p.Selected = false);
            if (Model.Persons[i].TrainingRole != null)
            {
                trainingRolesList.First(p => p.Value.ToString() == Model.Persons[i].TrainingRoleId.ToString()).Selected = true;
            }
            else
            {
                trainingRolesList.First(p => p.Value.ToString() == "2").Selected = true;
            }

            //Gets person costumes list
            var costumesList = (List<SelectListItem>)ViewBag.Costumes;
            costumesList.ForEach(p => p.Selected = false);
            if (Model.Persons[i].CostumeId == null)
            {
                costumesList.First(p => p.Value.ToString() == "0").Selected = true;
            }
            else
            {
                costumesList.First(p => p.Value.ToString() == Model.Persons[i].CostumeId.ToString()).Selected = true;
            }
            <tr>
                <td><label><input type="checkbox" value="@Model.Persons[i].Person.PersonId" name="AttendingPerson" checked="@check" title="@Model.Persons[i].Person.FirstLastName">@Model.Persons[i].Person.FirstLastName</label></td>
                <td>@Html.DropDownList("TrainingRoleId", trainingRolesList, htmlAttributes: new { @class = "form-control" })</td>
                <td>@Html.DropDownList("CostumeId", costumesList, htmlAttributes: new { @class = "form-control" })</td>
            </tr>
        }
    </table>

返回的值如下:

people  {string[3]} string[]
    [0] "1" string
    [1] "2" string
    [2] "3" string

roles   {string[4]} string[]
    [0] "1" string
    [1] "2" string
    [2] "2" string
    [3] "2" string

costumes    {string[4]} string[]
    [0] "1" string
    [1] "1" string
    [2] "0" string
    [3] "2" string

正如您所看到的那样,没有指标,选择了哪些人,但只返回了值。

0 个答案:

没有答案