I have a checkbox and button:
@using(Html.BeginForm())
{
I have tried out with input tag and it works as shown below:
<form method="post">
<input type="checkbox" id="chkRmb" name="chkRmb" /> Remember Me?
<input type="submit" value="Log In" class="btn btn-default login-btn" />
</form>
In the controller, compare the string value and convert its to a boolean.
bool rmbMe = (formdata["chkRmb"] ?? "").Equals("on", StringComparison.CurrentCultureIgnoreCase);
Try this, it solved this same issue for me. Thought I would share it in case others came upon this issue in the future.
[HttpPost]
public ActionResult Index(FormCollection collection)
{
Boolean tempValue = collection["showAll"] != null ? true : false;
TempData["showAll"] = tempValue;
...
something
...
}
I had trouble getting this to work and this is the solution I came up with. I'm showing it with an html helper.
@Html.CheckBoxFor(model => model.showAll, new { @class = "form-control", Name = "showAll"})
This is where I kept falling down and the following works.
bool MyBoolValue= (collection["showAll"] ?? "").Equals("true", StringComparison.CurrentCultureIgnoreCase);
So I gave this a shot and it seemed happy to take it, where collection is my FormCollection object:
if (collection.AllKeys.Contains("Inactive"))
{
np.Inactive = false;
}
else
{
np.Inactive = true;
}
Please be advised that the name of the targeted element is confusing - but this was the intended result I was seeking.
<input type="checkbox" name="showAll" id="showAll">Include completed
Will Post a value of "on"
or "off"
.
This WONT bind to a boolean,
To receive a boolean value you can use HTML Helper Checkbox Like
@Html.CheckBox("showAll")
<label for="showAll" style="display:inline">Include completed</label>
Update:
If checked the html helper will post back
"true,false"
and if unchecked as"false"
You can have this workaround as
bool MyBoolValue= Convert.ToBoolean(collection["showAll"].Split(',')[0]);
This is because the Html helpers class adds an extra hidden
field to save the state of the checkbox