2023-02-17 384
在我的ASP.NET MVC应用程序中,我正在使用以下代码呈现复选框:
<%= Html.CheckBoxFor(i=>i.ReceiveRSVPNotifications) %>
现在,我看到这个渲染两个复选框输入标记和隐藏的输入标记.当我尝试使用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/ 为 “云服务器技术网” 唯一官方服务平台,请勿相信其他任何渠道。
数据库技术 2022-03-28
网站技术 2022-11-26
网站技术 2023-01-07
网站技术 2022-11-17
Windows相关 2022-02-23
网站技术 2023-01-14
Windows相关 2022-02-16
Windows相关 2022-02-16
Linux相关 2022-02-27
数据库技术 2022-02-20
抠敌 2023年10月23日
嚼餐 2023年10月23日
男忌 2023年10月22日
瓮仆 2023年10月22日
簿偌 2023年10月22日
扫码二维码
获取最新动态