views:

140

answers:

1

Hi, this is probably simple but has been driving me nuts. I have searched all over for this and found people that have mentioned it but no solution provided.

I have a simple viewmodel that has a boolean property with no data annotations on, other properties do but these do not effect the problem.

Public Property AcceptSurvey As Boolean

I have a view that is strongly typed to this model that works fine with server validation (i.e. all other validation works fine and the AcceptSurvey is optional).

<%: Html.CheckBoxFor(Function(x) x.AcceptSurvey)%>

When I enable client side validation, on submitting the form (AcceptSurvey is not checked) I get the message "The AcceptSurvey field is required.". I presume this is because the validation only sees a value (true) when the checkbox is checked. I realise that the CheckBoxFor helper renders a hidden field (same name attribute and a value of false) and thought that this was to combat this.

If I make the property nullable I cannot use CheckBoxFor, I can use EditorFor but this renders as a dropdownlist with three properties (not what I want) and client-side validation works fine.

Am I being stupid? BTW I am using MVC JQuery for client side.

A: 

I don't know how great of an answer this is, but it worked for me.

I am using MVC 2.0 and so I created shared Display & Editor templates for the Boolean data type. I show the Boolean values as a two choice drop-down instead of a checkbox.

Another option would have been to have this same approach, but in the Editor template, create a hidden field and have the checkbox events set/reset the hidden field value. I started with this, but the users preferred the drop-down approach anyway.

/Views/Shared/EditorTemplates/Boolean.ascx

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.Boolean>" %>
<%
    var items = new List<SelectListItem>();
    items.Add(new SelectListItem(){
            Text = @"No",
            Value = @"false",
            Selected = (Model == false)
    });
    items.Add(new SelectListItem(){
            Text = @"Yes",
            Value = @"true",
            Selected = (Model == true)
    });
%>
<%: Html.DropDownList("", items) %>

/Views/Shared/EditorTemplates/Boolean.ascx

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.Boolean>" %>
<%: Model ? @"Yes" : @"No" %>
Tony