2
votes

I have a form containing a number of controls - nothing fancy:

@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    <fieldset>
        <legend>EmployeeViewModel</legend>
        <div class="editor-label">
            @Html.LabelFor(model => model.Employee.Title)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Employee.Title)
etc.....

UPDATE My ViewModel:

public class EmployeeCreateViewModel
    {
        public EmployeeCreateModel Employee { get; set; }
..etc

My Employee model:

public class EmployeeCreateModel
    {
        [Required]
        public string Title { get; set; }

        [DisplayName("Job Title")]
        [Required]
        public string JobTitle { get; set; }

        public bool Active { get; set; }
...etc

The Problem - I am using unobtrusive validation which works fine UNTIL I add a checkbox to the form. Regardless of the checkbox state, the form is submitted, bypassing client-side validation and errors are caught by the server-side validation. This is my checkbox:

<div class="editor-label">
   @Html.LabelFor(model => model.Employee.Active)
</div>
<div class="editor-field">
   @Html.CheckBoxFor(model => model.Employee.Active)
</div>

The checkbox model property is not a required field, so it doesn't need to be validated and I can see that it has a valid True/False value when it reaches the controller method.

Why is this happening, and how can I fix it?

1
So you don't want it to say false in the controller if it's unchecked?Andrew
@Andrew - the value passed to the controller IS false if it's uncheckedmarkpsmith
@markpsmith what errors are being caught by the server-side validation? Just because the checkbox has a value when it's unchecked doesn't mean it's being validated. It's just how checkboxes work in MVC. A bool has to be True or False, so when it's unchecked False is correct.Andrew
@Andrew - the checkbox is NOT one of the errors caught server-side, but I'm not interested in validating it anyway.markpsmith
Looks like others have had a similar problem. This question has no answers: stackoverflow.com/questions/18415655/…ED-209

1 Answers

3
votes

First, open javascript console (e.g., chrome inspector panel) and see if you are getting Uncaught TypeError: Object [object Object] has no method 'live' error from jquery.unobtrusive-ajax.js.

If you are seeing this error, you are probably using jquery 1.9.x or higher. If you check "Preserve log upon navigation" (chrome), you can see an error saying "Uncaught SyntaxError: Unexpected token u".

To solve this problem, include jquery migrate 1.2.x after jquery 1.9.x.

<script src="/Scripts/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.js"></script>

For details, see this post.