为什么ASP。净MVC Html。复选框输出两个名称相同的输入?

时间:2021-11-18 09:12:26

Why in the world does the line:

为什么世界上有这样一句话:

<%= Html.CheckBox("ForSale", Model.Product.ForSale)%> For Sale

result in the following HTML:

产生以下HTML:

<input id="ForSale" name="ForSale" type="checkbox" value="true" />
<input name="ForSale" type="hidden" value="false" />
For Sale

Now whenever I check the box and access Request.Form["ForSale"], I get the ridiculous answer of "true,false". Am I supposed to parse that?

现在,每当我选中复选框和访问请求时。从“待售”中,我得到了“true,false”的荒谬答案。我应该分析它吗?

This hidden field doesn't appear for the other HtmlHelper controls, so why does it for CheckBox?

这个隐藏字段不会出现在其他HtmlHelper控件中,那么为什么它会出现在复选框中呢?

How do I turn this stupid "feature" off? Or did the HtmlHelper just outgrow its usefulness?

我如何关闭这个愚蠢的“特性”?或者是HtmlHelper (html助手)已经不再有用了?

Update

更新

From the answer below, it seems that there is some logic behind this. I have prepared a little extension method so I don't have to think about it (thanks to @eu-ge-ne):

从下面的答案看来,这背后似乎有某种逻辑。我准备了一个扩展方法,所以我不需要考虑它(感谢@eu-ge-ne):

    public static bool GetCheckBoxValue(this System.Web.HttpRequestBase req, 
                                        string name) {
        return Convert.ToBoolean(req.Form.GetValues(name).First());
    }

7 个解决方案

#1


37  

It forces the field to be included if it's unchecked. If you uncheck a check box it doesn't get sent as part of the page - they are only sent if they're checked, and then there's a value of true. The hidden field ensures that false will be send if the check box is unchecked, as the hidden field is always sent.

如果字段未选中,则强制将其包含。如果您取消选中一个复选框,它不会作为页面的一部分发送——它们只在选中时发送,然后有一个值true。如果复选框未选中,则隐藏字段确保将发送false,因为隐藏字段总是被发送。

#2


3  

Here's how I've done it in one of my apps. Frustrating, but it seems to work.

以下是我如何在我的一个应用程序中完成的。令人沮丧,但这似乎行得通。

public virtual ActionResult Edit(int id, FormCollection values)
{
    SomeObject dbData = _repository.GetSomeObject(id);

    try
    {
        UpdateModel(dbData);
        if (values.GetValues("CheckBoxId").Contains("true")) 
            dbData.SomeBooleanProperty = true;
        else 
            dbData.SomeBooleanProperty = false;

        _repository.Save();

        Session["Success"] = "Successfully edited the part.";
        return RedirectToAction("Index");
    }
    catch
    {
        // Handle validation errors here
        return View(new SomeObjectFormViewModel(dbData));
    }
}

Hope this helps. If you've got any follow-up questions, just leave a comment and I'll update my answer accordingly.

希望这个有帮助。如果你有任何后续问题,请留下评论,我会相应地更新我的答案。

#3


3  

I took a different approach:

我采取了不同的方法:

Do not use the Html.CheckBoxFor or Html.CheckBox helper method to render a checkbox, but render it using normal html:

不要使用Html。CheckBoxFor或Html。复选框助手方法来呈现复选框,但使用普通的html呈现:

<input id="ShowOther" name="ShowOther" value="<%=Model.ShowOther %>" type="checkbox" <% if (Model.ShowOther)  { %>checked="checked"<% } %> />

And I've added a jQuery script which sets the value when the checkbox is checked/unchecked.

我还添加了一个jQuery脚本,它设置复选框被选中/选中时的值。

<script type="text/javascript">
    $(function() {
        $('#ShowOther').click(function() {
            var checked = $(this).attr('checked');
            if (checked != undefined)
                $(this).val(true);
            else
                $(this).val(false);
        });
    });
</script>

As far as I could test this, it seems that the correct value is always sent to the Controller, and no more issues with "true,false".

就我所能测试的来说,似乎正确的值总是被发送到控制器,并且不再有“true,false”的问题。

#4


2  

If a CheckBox is not checked, then it will not be included in the form submission. So this "feature" gives you a result for every CheckBox. Those that are not checked will be simply "false".

如果复选框没有选中,那么它将不会包含在表单提交中。所以这个“特性”为每个复选框提供了一个结果。那些没有被检查的将仅仅是“假的”。

I have implemented my own CheckBox helper functions that work differently. Most of the time I don't want just true or false, but just a collection of the values of the checked boxes. It's great for selecting certain items by their id on which to perform an action. I don't want the unchecked items even in the list.

我实现了自己的复选框助手函数,它们的工作方式不同。大多数情况下,我不希望仅仅是真或假,而只想要复选框的值的集合。选择特定的项目以执行操作是很好的。即使在列表中,我也不想要未选中的项。

You can take a look at the source code for the html extensions and use a similar structure to create your own CheckBox methods.

您可以查看html扩展的源代码,并使用类似的结构来创建自己的复选框方法。

http://aspnet.codeplex.com/sourcecontrol/changeset/view/23011?projectName=aspnet#288010

http://aspnet.codeplex.com/sourcecontrol/changeset/view/23011?projectName=aspnet # 288010

I would post mine, but I'm not using the standard HtmlHelper class, so it would probably be more confusing. I did add a value parameter to my CheckBox functions so that I can use a specific id value instead of "true" or "false".

我将发布我的,但是我没有使用标准的HtmlHelper类,所以它可能会更令人困惑。我在复选框函数中添加了一个值参数,这样我就可以使用一个特定的id值,而不是“true”或“false”。

#5


2  

Now whenever I check the box and access Request.Form["ForSale"], I get the ridiculous answer of "true,false". Am I supposed to parse that?

现在,每当我选中复选框和访问请求时。从“待售”中,我得到了“true,false”的荒谬答案。我应该分析它吗?

Try this:

试试这个:

var ForSale = Convert.ToBoolean(Request.Form.GetValues("ForSale").First());

UPDATED:

更新:

What if in the next MVC build it will return the value in the revers order "false, true"? ... – Mastermind

如果在下一个MVC构建中,它将返回revers顺序中的值“false, true”,该怎么办?…——策划

var ForSale = Request.Form.GetValues("ForSale")
    .Select(x => x.ToUpperInvariant()).Contains("TRUE");

// or

// FormatException can be thrown from Convert.ToBoolean()
var ForSale = Request.Form.GetValues("ForSale")
    .Select(x => Convert.ToBoolean(x)).Contains(true);

#6


0  

try

试一试

request.form["chkBoxes"].replace("false","").split(new char[] {','}, stringsplitoptions.removeemptyentries);

request.form .replace(“chkBoxes”)(“假”、“)。分割(新char[]{ ',' },stringsplitoptions.removeemptyentries);

#7


0  

I think the cleanest solution is to do:

我认为最干净的解决办法是:

(bool)formCollection["key"].ConvertTo(typeof(bool))

#1


37  

It forces the field to be included if it's unchecked. If you uncheck a check box it doesn't get sent as part of the page - they are only sent if they're checked, and then there's a value of true. The hidden field ensures that false will be send if the check box is unchecked, as the hidden field is always sent.

如果字段未选中,则强制将其包含。如果您取消选中一个复选框,它不会作为页面的一部分发送——它们只在选中时发送,然后有一个值true。如果复选框未选中,则隐藏字段确保将发送false,因为隐藏字段总是被发送。

#2


3  

Here's how I've done it in one of my apps. Frustrating, but it seems to work.

以下是我如何在我的一个应用程序中完成的。令人沮丧,但这似乎行得通。

public virtual ActionResult Edit(int id, FormCollection values)
{
    SomeObject dbData = _repository.GetSomeObject(id);

    try
    {
        UpdateModel(dbData);
        if (values.GetValues("CheckBoxId").Contains("true")) 
            dbData.SomeBooleanProperty = true;
        else 
            dbData.SomeBooleanProperty = false;

        _repository.Save();

        Session["Success"] = "Successfully edited the part.";
        return RedirectToAction("Index");
    }
    catch
    {
        // Handle validation errors here
        return View(new SomeObjectFormViewModel(dbData));
    }
}

Hope this helps. If you've got any follow-up questions, just leave a comment and I'll update my answer accordingly.

希望这个有帮助。如果你有任何后续问题,请留下评论,我会相应地更新我的答案。

#3


3  

I took a different approach:

我采取了不同的方法:

Do not use the Html.CheckBoxFor or Html.CheckBox helper method to render a checkbox, but render it using normal html:

不要使用Html。CheckBoxFor或Html。复选框助手方法来呈现复选框,但使用普通的html呈现:

<input id="ShowOther" name="ShowOther" value="<%=Model.ShowOther %>" type="checkbox" <% if (Model.ShowOther)  { %>checked="checked"<% } %> />

And I've added a jQuery script which sets the value when the checkbox is checked/unchecked.

我还添加了一个jQuery脚本,它设置复选框被选中/选中时的值。

<script type="text/javascript">
    $(function() {
        $('#ShowOther').click(function() {
            var checked = $(this).attr('checked');
            if (checked != undefined)
                $(this).val(true);
            else
                $(this).val(false);
        });
    });
</script>

As far as I could test this, it seems that the correct value is always sent to the Controller, and no more issues with "true,false".

就我所能测试的来说,似乎正确的值总是被发送到控制器,并且不再有“true,false”的问题。

#4


2  

If a CheckBox is not checked, then it will not be included in the form submission. So this "feature" gives you a result for every CheckBox. Those that are not checked will be simply "false".

如果复选框没有选中,那么它将不会包含在表单提交中。所以这个“特性”为每个复选框提供了一个结果。那些没有被检查的将仅仅是“假的”。

I have implemented my own CheckBox helper functions that work differently. Most of the time I don't want just true or false, but just a collection of the values of the checked boxes. It's great for selecting certain items by their id on which to perform an action. I don't want the unchecked items even in the list.

我实现了自己的复选框助手函数,它们的工作方式不同。大多数情况下,我不希望仅仅是真或假,而只想要复选框的值的集合。选择特定的项目以执行操作是很好的。即使在列表中,我也不想要未选中的项。

You can take a look at the source code for the html extensions and use a similar structure to create your own CheckBox methods.

您可以查看html扩展的源代码,并使用类似的结构来创建自己的复选框方法。

http://aspnet.codeplex.com/sourcecontrol/changeset/view/23011?projectName=aspnet#288010

http://aspnet.codeplex.com/sourcecontrol/changeset/view/23011?projectName=aspnet # 288010

I would post mine, but I'm not using the standard HtmlHelper class, so it would probably be more confusing. I did add a value parameter to my CheckBox functions so that I can use a specific id value instead of "true" or "false".

我将发布我的,但是我没有使用标准的HtmlHelper类,所以它可能会更令人困惑。我在复选框函数中添加了一个值参数,这样我就可以使用一个特定的id值,而不是“true”或“false”。

#5


2  

Now whenever I check the box and access Request.Form["ForSale"], I get the ridiculous answer of "true,false". Am I supposed to parse that?

现在,每当我选中复选框和访问请求时。从“待售”中,我得到了“true,false”的荒谬答案。我应该分析它吗?

Try this:

试试这个:

var ForSale = Convert.ToBoolean(Request.Form.GetValues("ForSale").First());

UPDATED:

更新:

What if in the next MVC build it will return the value in the revers order "false, true"? ... – Mastermind

如果在下一个MVC构建中,它将返回revers顺序中的值“false, true”,该怎么办?…——策划

var ForSale = Request.Form.GetValues("ForSale")
    .Select(x => x.ToUpperInvariant()).Contains("TRUE");

// or

// FormatException can be thrown from Convert.ToBoolean()
var ForSale = Request.Form.GetValues("ForSale")
    .Select(x => Convert.ToBoolean(x)).Contains(true);

#6


0  

try

试一试

request.form["chkBoxes"].replace("false","").split(new char[] {','}, stringsplitoptions.removeemptyentries);

request.form .replace(“chkBoxes”)(“假”、“)。分割(新char[]{ ',' },stringsplitoptions.removeemptyentries);

#7


0  

I think the cleanest solution is to do:

我认为最干净的解决办法是:

(bool)formCollection["key"].ConvertTo(typeof(bool))