2

这是我的代码:

@using (Html.BeginForm("AddMCondition", "Admin"))
{
  <td class="admin-textbox">
      @Html.TextBox("txtMCondition")
  </td>
  <td>
     @foreach (var exerType in Model.AllExerciseTypes)
     {
      <label>
         @Html.CheckBox("RestrictedType")
         @exerType.Name
      </label>
     }
       <input type="submit" value="Add Medical Condition" />
     </td>
 }

这就是我在控制器中检索值的方式

public ActionResult AddMCondition(string txtMCondition, string[] RestrictedType)
{
   //Code here...
}

AllExerciseTypes集合中只有 3 个项目。我注意到每个复选框都至少向控制器发送一个错误值,无论它是否被选中。如果我不选中任何复选框,我会在集合中得到 3 false。如果我选中 1 个复选框,我会得到 4 个值,即 1 个真值和 3 个假值,依此类推。当我检查所有这些时,我得到 3 个值,即 True、False、True、False、True 和 False。

有什么理由,复选框在每种情况下都至少发送错误?

4

1 回答 1

0

This is because the Html Helper for a checkbox adds an extra hidden field with a value of false to ensure that something is posted back to the server even if the checkbox is not checked. If you add <input type="checkbox" name="cbSomething" value="true"/> to your form and post it back without checking the checkbox then you won't get a value sent back to the server. If you use the strongly typed helper extension (Html.CheckBoxFor(m => m.RestrictedType) for example) and bind a checkbox to a property on your model, the model binder will correctly bind the value to the model property. Here's the code snippet from the input extensions within MVC:

  if (inputType != InputType.CheckBox)
    return TagBuilderExtensions.ToMvcHtmlString(tagBuilder1, TagRenderMode.SelfClosing);
  StringBuilder stringBuilder = new StringBuilder();
  stringBuilder.Append(tagBuilder1.ToString(TagRenderMode.SelfClosing));
  TagBuilder tagBuilder2 = new TagBuilder("input");
  tagBuilder2.MergeAttribute("type", HtmlHelper.GetInputTypeString(InputType.Hidden));
  tagBuilder2.MergeAttribute("name", fullHtmlFieldName);
  tagBuilder2.MergeAttribute("value", "false");
  stringBuilder.Append(tagBuilder2.ToString(TagRenderMode.SelfClosing));
  return MvcHtmlString.Create(((object) stringBuilder).ToString());
于 2013-05-11T20:29:07.107 回答