在我的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集合似乎将这两个值连接在一起,因为它们具有相同的名称。
有什么想法吗?
发布于 2012-03-12 19:30:14
我和Shawn (上图)也有同样的问题。这种方法对于POST来说可能很好,但是对于GET来说它真的很糟糕。因此,我实现了一个简单的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框架的更改破坏我的代码。所以我必须确保我有测试覆盖率来解释这个新合同。
发布于 2013-05-03 08:32:25
附加输入标记的Here is the 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", fullName);
hiddenInput.MergeAttribute("value", "false");
inputItemBuilder.Append(hiddenInput.ToString(TagRenderMode.SelfClosing));
return MvcHtmlString.Create(inputItemBuilder.ToString());
}
发布于 2015-04-20 00:29:56
我认为最简单的解决方案是直接呈现输入元素,如下所示:
<input type="checkbox"
id="<%=Html.IdFor(i => i.ReceiveRSVPNotifications)%>"
name="<%=Html.NameFor(i => i.ReceiveRSVPNotifications)%>"
value="true"
checked="<%=Model.ReceiveRSVPNotifications ? "checked" : String.Empty %>" />
在Razor语法中,这甚至更简单,因为当给出一个'true‘服务器端值时,'checked’属性直接呈现为一个"checked“值。
https://stackoverflow.com/questions/2860940
复制相似问题