为什么CheckBoxFor会呈现一个额外的输入标签,我怎样才能使用FormCollection获得数值?

 2023-02-17    321  

问题描述

在我的ASP.NET MVC应用程序中,我正在使用以下代码呈现复选框:

<%= Html.CheckBoxFor(i=>i.ReceiveRSVPNotifications) %>

现在,我看到这个渲染两个复选框输入标记和隐藏的输入标记.当我尝试使用FormCollection检索复选框时,我有问题是:

为什么CheckBoxFor会呈现一个额外的输入标签,我怎样才能使用FormCollection获得数值?

FormValues["ReceiveRSVPNotifications"]

我得到了值”true,false”.在查看呈现的HTML时,我可以看到以下内容:

<input id="ReceiveRSVPNotifications" name="ReceiveRSVPNotifications" value="true" type="checkbox">
 <input name="ReceiveRSVPNotifications" value="false" type="hidden">

所以FormValues集合似乎加入这两个值,因为它们具有相同的名称.

任何想法?

推荐答案

在这里看看:

这不是一个bug,实际上是标准的同样的方法
轨道和单轨式使用.

当您使用复选框提交表单时,该值仅发布,如果
检查复选框.所以,如果你没有选中的复选框那么
在许多情况下,什么都不会被发送到服务器
想要发送错误.由于隐藏的输入具有相同的名称
作为复选框,那么如果复选框未被选中,您仍然会得到一个
“假”发送到服务器.

检查复选框后,ModelBinder会自动采取
从”真假”

中提取”真实”的关心

其他推荐答案

我的问题与shawn(上图)相同.这种方法可能很棒,但它真的很糟糕.因此,我实现了一个简单的HTML扩展,只需删除隐藏的字段.

public static MvcHtmlString BasicCheckBoxFor<T>(this HtmlHelper<T> html, 
                                                Expression<Func<T, bool>> expression,
                                                object htmlAttributes = null)
{
    var result = html.CheckBoxFor(expression).ToString();
    const string pattern = @"<input name=""[^""]+"" type=""hidden"" value=""false"" />";
    var single = Regex.Replace(result, pattern, "");
    return MvcHtmlString.Create(single);
}

我现在的问题是我不希望改变mvc框架来打破我的代码.所以我必须确保我有测试覆盖,解释了这份新合同.

其他推荐答案

我使用此替代方法呈现get表单的复选框:

/// <summary>
/// Renders checkbox as one input (normal Html.CheckBoxFor renders two inputs: checkbox and hidden)
/// </summary>
public static MvcHtmlString BasicCheckBoxFor<T>(this HtmlHelper<T> html, Expression<Func<T, bool>> expression, object htmlAttributes = null)
{
    var tag = new TagBuilder("input");

    tag.Attributes["type"] = "checkbox";
    tag.Attributes["id"] = html.IdFor(expression).ToString();
    tag.Attributes["name"] = html.NameFor(expression).ToString();
    tag.Attributes["value"] = "true";

    // set the "checked" attribute if true
    ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
    if (metadata.Model != null)
    {
        bool modelChecked;
        if (Boolean.TryParse(metadata.Model.ToString(), out modelChecked))
        {
            if (modelChecked)
            {
                tag.Attributes["checked"] = "checked";
            }
        }
    }

    // merge custom attributes
    tag.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));

    var tagString = tag.ToString(TagRenderMode.SelfClosing);
    return MvcHtmlString.Create(tagString);
}

它类似于 Chris Kemp 的方法,该方法正常工作,除了这个不使用底层CheckBoxFor和Regex.Replace.它基于原始Html.CheckBoxFor方法的来源.

以上所述是小编给大家介绍的为什么CheckBoxFor会呈现一个额外的输入标签,我怎样才能使用FormCollection获得数值?,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对77isp云服务器技术网的支持!

原文链接:https://77isp.com/post/34266.html

=========================================

https://77isp.com/ 为 “云服务器技术网” 唯一官方服务平台,请勿相信其他任何渠道。