user3378165
user3378165

Reputation: 6916

Check if checkbox is checked MVC controller

On my MVC View I have a few checkboxes:

<form method="POST" id="formRegistration" action="Registration/SubmitRegistration" > 
//Other code...
    <input name="test1" type="checkbox" />
    <input name="test2" type="checkbox"  />
</form>

On the controller I get- using a POST request- the data and I insert it to the DataBase:

public void AddRegistered(Registration r)
{
//Other code...
     dParameters.Add("test1", r.test1.ToString());
     dParameters.Add("test2", r.test2.ToString());
//Other code...
}

The problem is that I keep getting a false value even if the checkbox is checked.

Wham am I missing?

Upvotes: 0

Views: 7197

Answers (3)

Burak Altin
Burak Altin

Reputation: 468

If you don't want to use HtmlHelper class you can do like this

<form method="POST" id="formRegistration" action="Registration/SubmitRegistration" > 

<input name="test1" type="checkbox" value="@Model.test1" />
<input name="test2" type="checkbox" value="@Model.test2"  />

test1 and test2 should be in your model class.

Upvotes: 1

Dusan
Dusan

Reputation: 5144

You are missing the value attribute:

<input name="test1" type="checkbox" value="true" />
<input name="test2" type="checkbox" value="true" />

As simple as that.

Upvotes: 1

caesay
caesay

Reputation: 17233

So the first thing you should do it take a look at the actual data being sent to the server with chrome debug tools or similar. What you might find is that your checkbox value will be set to on if checked, or it will be missing completely if un-checked.

One suggestion in the comments was @Html.CheckBoxFor, but this also suffers the fact that nothing will be sent if the checkbox is un-checked and in specific situations that can still become a problem.

You have two solutions - fix it on the client, or fix it on the server.

Fix it on the client:
To do this, you'll need to (with javascript) add a hidden field for every checkbox. Forgive me, I'm not by an editor to test it out but it might look something like this (from memory):

$('input[type="checkbox"]').each(function(el) {
    var hidden = $('<input type="hidden" />');
    hidden.name = el.name;
    el.after(hidden);
    el.on("change", function(el) {
       hidden.value = el.checked ? "true" : "false";
    });
});

Fix it on the server:
To do this, you'll need to create a custom PropertyBinder which recognizes on as a boolean true. This would be set on a property-attribute level. You could alternatively override the global ModelBinder to do this so you don't need to specifically annotate a property for this to work.


Personally, I prefer the "fix it on the client" method, because you will get either true or false posted back to the server every time which is what you'd expect and is the closest to the way that HtmlHelper does it.

Upvotes: 1

Related Questions