Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get checkbox value from FormCollection?

I have a checkbox and button:

@using(Html.BeginForm())
{
    <div id="search-block">
        <input type="checkbox" name="showAll" id="showAll">Include completed
        <input type="submit" value="Apply"/>
    </div>
}

and second thing in controller:

[HttpPost]
public ActionResult Index(FormCollection collection)
{
    var showAll = collection["showAll"];
    TempData["showAll"] = showAll;

    ... 
    something
    ...
}

It's actually working, BUT:

If checkboxes are not checked, I am receiving null (doesn't bother me much).

If checkboxes are checked, I am receiving "on" from FormCollection, and this is not what I need. I want to receive true or false.

How can I do this?

like image 644
Olegs Jasjko Avatar asked Mar 11 '15 12:03

Olegs Jasjko


People also ask

Does checkbox have value attribute?

Note: Unlike other input controls, a checkbox's value is only included in the submitted data if the checkbox is currently checked . If it is, then the value of the checkbox's value attribute is reported as the input's value.

What value does checkbox return?

Return Value: It returns a string value that represents the value of the value attribute of a input checkbox field.


1 Answers

Try this

bool MyBoolValue= collection["showAll"].Count > 1;

when 1 then false

when 2 then true

like image 145
marcinJ Avatar answered Sep 23 '22 18:09

marcinJ