5

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?

1
  • I've updated my solution to further take care of the server side binding problem you were having. Commented Sep 2, 2011 at 19:06

3 Answers 3

8

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!

Sign up to request clarification or add additional context in comments.

1 Comment

I implement a javascript code to change the "value" property when click the checkbox: $(":checkbox").live("change", function () { if (this.checked) { this.value = "T"; } else { this.value = "F"; } }); but this only works when it is checked. When is unchecked the value binded is null.
0

When you set the checkstate of the new checkbox items, just put an if statement:

checkBox1.Checked = (stringValue == "T") ? true : false;

Comments

0

I made my own extension to solve this problem. It is a little tidyer in the razorview, helps minimizing the c# / razor mixture. Here's the class:

public static class CheckBoxExtensions {

    public static MvcHtmlString ValueCheckbox<TModel>(this HtmlHelper<TModel> htmlHelper, string name, string value, bool isChecked, IDictionary<string, object> htmlAttributes, bool disabled = false)
    {
        string result = string.Format(CultureInfo.InvariantCulture, 
            "<input type=\"checkbox\" name=\"{0}\" value=\"{1}\" {2} {3} ",
            name, value, (isChecked) ? "checked=\"checked\"" : "", (disabled) ? "disabled=\"disabled\"" : "");

        if (htmlAttributes != null && htmlAttributes.Count > 0)
        {
            foreach (KeyValuePair<string, object> item in htmlAttributes)
            {
                result += string.Format(CultureInfo.InvariantCulture, "{0}=\"{1}\" ", item.Key, item.Value.ToString());
            }
        }

        result += " />";

        return new MvcHtmlString(result);
    } 
}

And this is what I do in the razorview:

Html.ValueCheckbox("SelectedItems", 
    item.Number, 
    (Model.SelectedItems.Contains(item.Number)), 
    new Dictionary<string, object>() { 
        { "data-disable-bubble", "true" }, 
        { "data-forms-enable-any-checked-checkbox", "true" } 
    }
)

Dont mind the weir HtmlAttributes, I figured I would just let them in there :-)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.