开发者

Why Html.Checkbox("Visible") returns "true, false" in ASP.NET MVC 2?

开发者 https://www.devze.com 2023-03-03 17:44 出处:网络
I\'m using Html.Checkbox(\"Visible\") for displaying a check box to user. In post back, FormCollect开发者_JAVA百科ion[\"Visible\"] value is \"true, false\". Why?

I'm using Html.Checkbox("Visible") for displaying a check box to user. In post back, FormCollect开发者_JAVA百科ion["Visible"] value is "true, false". Why?

in view:

<td>                
    <%: Html.CheckBox("Visible") %>
</td>

in controller:

 adslService.Visible = bool.Parse(collection["Visible"]);


That's because the CheckBox helper generates an additional hidden field with the same name as the checkbox (you can see it by browsing the generated source code):

<input checked="checked" id="Visible" name="Visible" type="checkbox" value="true" />
<input name="Visible" type="hidden" value="false" />

So both values are sent to the controller action when you submit the form. Here's a comment directly from the ASP.NET MVC source code explaining the reasoning behind this additional hidden field:

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.
    ...

Instead of using FormCollection I would recommend you using view models as action parameters or directly scalar types and leave the hassle of parsing to the default model binder:

public ActionResult SomeAction(bool visible)
{
    ...
}


I've recently dealt with this issue and came up with a method of bypassing the MVC binding and using Contains("true") on the query string. Nothing else worked for me.

If people are stuck with the other answers then this is what worked for me - http://websitesorcery.com/post/2012/03/19/CheckBox-Issue-with-MVC-3-WebGrid-Paging-Sorting.aspx


If you want/need to use FormCollection, instead of checking for true or false, check for true,false or false.

e.g. instead of this

adslService.Visible = bool.Parse(collection["Visible"]);

do this

adslService.Visible = bool.Parse(collection["Visible"] != "false");


I had the same issue. I fixed it with the following combination (with a little help from Darin Dimitrov--thank you):

VIEW:

<label for="optIn"><%=Html.CheckBox("optIn", ViewData["OptIn"])%>

Controller:

public ActionResult Index()
{
   ViewData["Optin"] = True;
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(FormCollection form, bool OptIn )
{        
    ViewData["Optin"] = OptIn;
}

Here's the source for the control with and without the checkbox actually checked (for reference):

Checked:

<input Length="4" checked="checked" id="optIn" name="optIn" type="checkbox" value="true" /><input name="optIn" type="hidden" value="false" />

Unchecked:

<input Length="4" id="optIn" name="optIn" type="checkbox" value="true" /><input name="optIn" type="hidden" value="false" />

So, here's how I am interpreting the behavior:

HTML will not post back the field value if the checkbox is unchecked but will post back if it is. The helper appends a hidden field after the checkbox control (value of 'False'). If the checkbox is checked, the source shows "checked = 'checked'" if it's unchecked, this does not appear. So, if checked = checked, true is passed back to the controller. If the box is unchecked, the control is not passed back so the hidden field, named the same, takes over and passes back a false. This way you have both conditions. Strange but it works. I hope this helps.


I had the same issue in MVC 4,

This solution worked for me.

My (form)View:

@Html.EditorFor(m =>  m.SomeBoolValue)

For voiding the duplicate "true,false" values when CheckBox is true

I stored the CheckBox param in an array:

var arrParams = Request.Form["SomeBoolValue"].Split(',');

Grab the first element:

string sParam = arrParams[0].ToString();

Parse it:

bool BoolValue = bool.Parse(sParam);

Keep it:

MyObject.SomeBoolValue = BoolValue;


The default behaviour of the MVC Entension for Html.Checkbox, generates a hidden field along with it to be posted. In my case, Because the custom checkbox I have added to page is not model binded like Html.CheckBoxFor, I have decided to make it as simple html checkbox.

<input type="checkbox" name="WithAttachment" checked="checked"/> Include Attachments

This may sound silly, but would save someone's time than running after work arounds. This will prevent from creating a checkbox using MVC extension


I already have a static function that I use everywhere to handle boolean type text and return true or false as a boolean so I just take care of it there

            if (sBool.StartsWith("true,")) bReturn = true;//cater for mvc checkboxes

            else if (sBool == "true") bReturn = true;

            else if (sBool == "t") bReturn = true;//t-f

            else if (sBool == "1") bReturn = true;//1-0

            else if (sBool == "yes") bReturn = true;//yes-no

            else if (sBool == "y") bReturn = true;//y-n

            else if (sBool == "on") bReturn = true;//on-off
0

精彩评论

暂无评论...
验证码 换一张
取 消