asp.net-mvc MVC Html.CheckBox 和表单提交问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/658458/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-07 23:25:26  来源:igfitidea点击:

MVC Html.CheckBox and form submit issue

asp.net-mvccheckbox

提问by Andriy Tkach

Crazy issue with submitting of values in Html.Checkbox in ASP.NET MVC RC

在 ASP.NET MVC RC 中提交 Html.Checkbox 中的值的疯狂问题

Some of the values are just not come to Request.Params

一些值只是没有来到 Request.Params

At my form I have this line inside the cycle:

<%=Html.CheckBox("cb" + p.Option.Id, p.Option.IsAllowed, new { value = 6 })%>

在我的表单中,我在循环中有这一行:

<%=Html.CheckBox("cb" + p.Option.Id, p.Option.IsAllowed, new { value = 6 })%>

and it renders to next:

它呈现到下一个:

    <input checked="checked" id="cb17" name="cb17" type="checkbox" value="6" />
<input name="cb17" type="hidden" value="false" /> 

    <input checked="checked" id="cb18" name="cb18" type="checkbox" value="6" />
<input name="cb18" type="hidden" value="false" /> 

    <input id="cb19" name="cb19" type="checkbox" value="6" />
<input name="cb19" type="hidden" value="false" />

    <input id="cb20" name="cb20" type="checkbox" value="6" />
<input name="cb20" type="hidden" value="false" />

    <input checked="checked" id="cb21" name="cb21" type="checkbox" value="6" />
<input name="cb21" type="hidden" value="false" /> 

After submitting the Form I'm get something like:

提交表格后,我得到如下信息:

Form.Params["cb17"] = {6, "false"}
Form.Params["cb18"] = {6, "false"}
Form.Params["cb19"] = {"false"}
Form.Params["cb20"] = {"6,false"}
Form.Params["cb21"] = {"false"}

In the request string Some of the params are displayed twice (normal situation) and some only ONE TIME (only value of hidden field). It seems that it doesn't rely on whether checkbox was checked or not, whether value has changed or so...

在请求字符串中,有些参数显示两次(正常情况),有些只显示一次(仅隐藏字段的值)。似乎它不依赖于是否选中了复选框,值是否已更改等等......

Does anybody faced with such a situation? How can I work around?

有人遇到过这种情况吗?我该如何解决?

回答by TStamper

   <% using(Html.BeginForm("Retrieve", "Home")) %>//Retrieve is the name of the action while Home is the name of the controller
       <% { %>
    <%foreach (var app in newApps)              { %>  
  <tr> 
       <td><%=Html.CheckBox(""+app.ApplicationId )%></td>      

   </tr>  
<%} %>
 <input type"submit"/>
<% } %>

and in your controller

并在您的控制器中

 List<app>=newApps; //Database bind
 for(int i=0; i<app.Count;i++)
 {

    var checkbox=Request.Form[""+app[i].ApplicationId];
    if(checkbox!="false")// if not false then true,false is returned
 }

the reason you check for false because the Html Checkbox helper does some kind of freaky thing for value true

您检查 false 的原因是因为 Html Checkbox 助手为 true 值做了某种奇怪的事情

True returns as:

True 返回为:

it makes the string read "true, false"

so you may have thought it was two values but its just one and means true

所以你可能认为它是两个值,但它只是一个并且意味着真的

False returns as:

假返回为:

it makes the string read "false"

回答by veggerby

This is actually the way it should work according to specifications.

这实际上是它应该根据规范工作的方式。

It has nothing to do with ASP.NET MVC, but when a check box is left unchecked it is notincluded in the POST collection.

它与 ASP.NET MVC 无关,但是当复选框未选中时,它不会包含在 POST 集合中。

You get two values because you have both a checkbox and an input with the same name (and the ones you have two values for are most likely the ones with checkboxes checked).

你得到两个值,因为你有一个复选框和一个同名的输入(你有两个值的那些很可能是选中了复选框的那些)。

Edit: specificationsfrom W3C

编辑:规格从W3C

回答by Andriy Tkach

Without the need to ask database about the ids after form submitting/before saving (Stateless mode) I've produced such code:

无需在表单提交后/保存前(无状态模式)向数据库询问 id,我已经生成了这样的代码:

    foreach (string key in Request.Form)
    {
        var checkbox = String.Empty;
        if (key.StartsWith("cb"))
        {
          checkbox = Request.Form["" + key];

          if (checkbox != "false")
          {
              int id = Convert.ToInt32(key.Remove(0, 2));
          }
        }
    }

Thanks you guys to help me work around this issue!

谢谢你们帮我解决这个问题!

回答by Lord of Scripts

I use this:

我用这个:

public struct EditedCheckboxValue
{
    public bool Current { get; private set; }

    public bool Previous { get; private set; }

    public bool Changed { get; private set; }

    public EditedCheckboxValue(System.Web.Mvc.FormCollection collection, string checkboxID) : this()
    {
        string[] values = collection[checkboxID].Split(new char[] { ',' });
        if (values.Length == 2)
        {   // checkbox value changed, Format: current,old
            Current = bool.Parse(values[0]);
            Previous = bool.Parse(values[1]);
            Changed = (Current != Previous);
        }
        else if (values.Length == 1)
        {
            Current = bool.Parse(values[0]);
            Previous = Current;
            Changed = false;
        }
        else
            throw new FormatException("invalid format for edited checkbox value in FormCollection");
    }
}

and then call it like this:

然后像这样调用它:

EditedCheckboxValue issomething = new EditedCheckboxValue(collection, "FieldName");
instance.IsSomething = issomething.Current;