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?
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.
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With