从复选框到选择的视图到控制器的MVC传递ID

时间:2019-06-19 09:09:01

标签: asp.net-mvc

目前,我有一个表格,其中每个ID用户的列均带有复选框。我想将该值从视图中选中的复选框传递到控制器,以执行actionresult CreatePlanning中的某些操作。 我该怎么做 ?

<td data-field="@Html.DisplayNameFor(model => model.Status_Coordinator)">
                    @Html.DisplayFor(model => item.Status_Coordinator)
                    <input id="Status_Coordinator" type="checkbox" name="Status_Coordinator" value="true" />
                </td>

2 个答案:

答案 0 :(得分:0)

可能还有其他方法可以执行此操作,但是我以前已经做到了-创建一个新的Checkbox类,例如:

public class CheckboxModel
{
    //Value of checkbox 
    public int Value { get; set; }
    //description of checkbox 
    public string Text { get; set; }
    //whether the checkbox is selected or not
    public bool IsChecked { get; set; }
}

初始化静态用户列表,以给您一个想法(您可能必须动态生成它):

ListOfUserID = new List<CheckboxModel>
               { 
                  new CheckboxModel { Value = 1, Text = "User1" },
                  new CheckboxModel { Value = 2, Text = "User2" },
                  new CheckboxModel { Value = 3, Text = "User3" }     
                };

在视图中使用此类(例如,在循环中使用):

@Html.CheckBoxFor(m => Model.ListOfUserID[i].IsChecked)@Model.ListOfUserID[i].Text
@Html.HiddenFor(m => Model.ListOfUserID[i].Value)
@Html.HiddenFor(m => Model.ListOfUserID[i].Text)  

然后,在发布表单时,在“控制器”操作中具有复选框的文本或值。

答案 1 :(得分:0)

选择使用复选框 `

选择您的订单:

@foreach(模型中的 var x) { @Html.CheckBoxFor(modelItem => x.isSelected, new { @id="test" ,value = (x.Orderumber) }) } 获取值

将值传递给控制器​​使用 JQuery 为:

<script>
$(document).ready(function () {
    $("#b1").click(function () {
        var favorite = [];
        $.each($("input[name='x.isSelected']:checked"), function () {
            favorite.push($(this).val());
        });
        alert("Your order are: " + favorite.join(", "));
        window.location.replace("https://localhost:44304/SecondPage/? 
       id="+favorite.join(", "));
          });
        });
       </script>