与Asp.net mvc 2中的复选框空隐藏字段

时间:2010-12-11 13:55:50

标签: asp.net-mvc-2

当我在Asp.net MVC 2中创建一个Html.CheckBox()时,我想知道当我查看它的html时,还有一个带有该复选框的隐藏字段,隐藏字段的来源和目的是什么? / p>

1 个答案:

答案 0 :(得分:4)

来自ASP.NET MVC中的评论source code

if (inputType == InputType.CheckBox) {
    // Render an additional <input type="hidden".../> for checkboxes. This
    // addresses scenarios where unchecked checkboxes are not sent in the request.
    // Sending a hidden input makes it possible to know that the checkbox was present
    // on the page when the request was submitted.
    StringBuilder inputItemBuilder = new StringBuilder();
    inputItemBuilder.Append(tagBuilder.ToString(TagRenderMode.SelfClosing));

    TagBuilder hiddenInput = new TagBuilder("input");
    hiddenInput.MergeAttribute("type", HtmlHelper.GetInputTypeString(InputType.Hidden));
    hiddenInput.MergeAttribute("name", name);
    hiddenInput.MergeAttribute("value", "false");
    inputItemBuilder.Append(hiddenInput.ToString(TagRenderMode.SelfClosing));
    return inputItemBuilder.ToString();
}

例如,如果用户没有检查该值,则没有任何内容发送到服务器,因此如果您在后期操作中绑定某些视图模型,则不会有任何值。隐藏字段发送false

的值