Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind checkbox to a string property in asp net mvc

I had in my classes some fields that represents true or false, but it has string values "T" or "F".

How to bind the checkbox to these fields?

like image 943
Beetlejuice Avatar asked Sep 02 '11 16:09

Beetlejuice


1 Answers

You can do this in ASP.Net MVC Razor

<input type="checkbox" name="someName" value="@Model.SomeValue" 
@(Model.IsChecked == "T" ? "checked='checked'" : "") />

However, this may not be what you are looking for, since you would have to do some manual work on the server to figure out values that had been "unchecked".

By default only your checked values will get sent to the server.

UPDATE:

The Html.CheckBox and Html.CheckBoxFor helper methods both emit hidden fields in order to make sure everything binds correctly back to your model. You can imitate this behavior pretty easily.

First you need to emit a hidden field that will be bound to your model on the server.

@Html.HiddenFor(model => model.StringBool, new { id = "_stringBool" })

Next you create a plain jane checkbox and set the initial state to reflect your model.

<input type="checkbox" id="myCheckBox" @(Model.StringBool == "T" ? "checked='checked'" : "") />

This checkbox's only purpose is to proxy values to and from the hidden field so your model will automatically get bound on the server. This can be achieved with some simple jQuery.

$("#myCheckBox").click(function () {
   var isChecked = $(this).is(":checked");

   $("#_stringBool").val(isChecked ? "T" : "F");
});

Now checking and unchecking the box will set the value of your bound hidden field accordingly. When you post to the server your values will be preserved via model binding.

Some things to note

This does not take into account validation. It is very easy to change the value of the hidden field so make sure you properly validate on the server side!

like image 57
Josh Avatar answered Oct 31 '22 18:10

Josh