如何将多个单选按钮值绑定到控制器操作

时间:2017-07-06 12:14:40

标签: c# asp.net-mvc model-binding

以下是我的视图代码,我从控制器传递列表到视图,在这里我通过foreach迭代该列表我想在提交表单时将相同的视图模型列表传递给操作

@model IEnumerable<AskQuestionViewModel>
.
.
.
<table class="table table-bordered">
 <thead>
   <tr>
     <td>Question</td>
     <td>Yes</td>
     <td>No</td>
     </tr>
 </thead>
 <tbody>
   @foreach (var q in Model)
   {
     <tr>
        <td>@q.Question</td>
        @if (q.Answer == true)
        {
          <td><input type="radio" name="@q.QuestionID" value="true" checked />/td>
        }
        else
        {
          <td><input type="radio" name=@q.QuestionID value="true" required /></td>
        }

        @if (q.Answer == false)
        {
           <td><input type="radio" name=@q.QuestionID value="false" checked /></td>
        }
        else
        {
           <td><input type="radio" name=@q.QuestionID value="false" required /></td>
        }
        </tr>
   }

 

以下是行动代码

[HttpPost]
public ActionResult AskQuestions(List<AskQuestionViewModel> askQVM)
{
    ...
}

我在askQVM中得到null

1 个答案:

答案 0 :(得分:1)

这就是回发所需要的。

    <table class="table table-bordered">
        <thead>
            <tr>
                <td>Question</td>
                <td>Yes</td>
                <td>No</td>
            </tr>
        </thead>
        <tbody>
            @using (Html.BeginForm("AskQuestions", "Questions", FormMethod.Post))
            {                   

                for (int i = 0; i < Model.Count; i++)
                {                   
                    var yesOptions = Model[i].Answer ? new { @checked = "checked" } : null;
                    var noOptions = Model[i].Answer ? null : new { @checked = "checked" };
                    <tr>
                        <td>
                            @Model[i].Question
                            @Html.HiddenFor(model=>Model[i].QuestionID)
                            @Html.HiddenFor(model=>Model[i].Question)
                        </td>
                        <td>@Html.RadioButtonFor(model => Model[i].Answer, true, yesOptions)</td>
                        <td>@Html.RadioButtonFor(model => Model[i].Answer, false, noOptions)</td>
                    </tr>
                }
                <button type="submit">Submit</button>
            }
        </tbody>
    </table>