0

Weird this one.

On my .NET MVC 4 project I've added a file on App_Code who contains this method:

@helper CheckBox(string name, bool isChecked = false, string className = "") {
  <div class="checkboxHolder">
    <input id="@name" name="@name" type="hidden" value="@isChecked") />
    <i class="@className checkboxBts fa @((isChecked) ? "fa-check-square-o" : "fa-square-o")" data-checkbox-associated="@name"></i>
  </div>
}

I'm using it to style checkboxes using font-awesome, so my app checkboxes are made of an input type hidden who stores a boolean value and an icon to give feedback to users.

Weird thing is, on executing when isChecked == false, the hidden returned by this method is like:

<input id="myCheckboxId" name="myCheckboxId" type="hidden" />

There is no value at all, when I try to save it to the model an exception is thrown saying that model cannot be saved.

I've fixed it changing the method to use:

<input id="@name" name="@name" type="hidden" @((isChecked) ? "value=true" : "value=false") />

Which is working fine. However, I wonder if anyone know what could be happening on the original output.

Thank you all.

Bardo
  • 2,470
  • 2
  • 24
  • 42
  • 1
    This is by design, it was a change introduced in MVC 4, IIRC. See this: http://www.davidhayden.me/blog/conditional-attributes-in-razor-view-engine-and-asp.net-mvc-4. – Ricardo Peres Jan 08 '15 at 10:26

1 Answers1

0

It's not entirely a duplicate, but this is answered in Why is my hidden input writing: value=“value” instead of true/false?:

if you have:

<input name="somefield" type="hidden" someprop="@(SomeBooleanExpression)"/>

[and @SomeBooleanExpression] is false it is omitted completely:

<input name="somefield" type="hidden"/>

To get around this, consider .ToString()

So, use:

<input id="@name" name="@name" type="hidden" value="value="@(isChecked.ToString())" />
Community
  • 1
  • 1
CodeCaster
  • 147,647
  • 23
  • 218
  • 272