Do checkbox inputs only post data if they're checked?

后端 未结 12 760
盖世英雄少女心
盖世英雄少女心 2020-11-22 08:04

Is it standard behaviour for browsers to only send the checkbox input value data if it is checked upon form submission?

And if no value data is supplied, is the defa

12条回答
  •  礼貌的吻别
    2020-11-22 08:51

    In HTML, each element is associated with a single (but not unique) name and value pair. This pair is sent in the subsequent request (in this case, a POST request body) only if the is "successful".

    So if you have these inputs in your

    DOM:

    
    
    
    
    
    
    
    
    
    
    
    
    
    

    Will generate these name+value pairs which will be submitted to the server:

    one=foo
    three=first
    three=second
    five=baz
    eight=grault
    

    Notice that:

    • two and six were excluded because they had the disabled attribute set.
    • three was sent twice because it had two valid inputs with the same name.
    • four was not sent because it is a checkbox that was not checked
    • six was not sent despite being checked because the disabled attribute has a higher precedence.
    • seven does not have a name="" attribute sent, so it is not submitted.

    With respect to your question: you can see that a checkbox that is not checked will therefore not have its name+value pair sent to the server - but other inputs that share the same name will be sent with it.

    Frameworks like ASP.NET MVC work around this by (surreptitiously) pairing every checkbox input with a hidden input in the rendered HTML, like so:

    @Html.CheckBoxFor( m => m.SomeBooleanProperty )
    

    Renders:

    
    
    

    If the user does not check the checkbox, then the following will be sent to the server:

    SomeBooleanProperty=false
    

    If the user does check the checkbox, then both will be sent:

    SomeBooleanProperty=true
    SomeBooleanProperty=false
    

    But the server will ignore the =false version because it sees the =true version, and so if it does not see =true it can determine that the checkbox was rendered and that the user did not check it - as opposed to the SomeBooleanProperty inputs not being rendered at all.

提交回复
热议问题