40

Given the following viewmodel:

public class FooViewModel
{
    public bool IsBoolValue { get; set; }
}

and this view:

<input type="hidden" id="Whatever" data-something="@Model.IsBoolValue" value="@Model.IsBoolValue" />

The output of the hidden input field is this:

<input type="hidden" id="Whatever" data-something="True" value="value">

How come the value attribute is not set toTrue, but the data-something attribute is?

Is there a change in MVC 5 that would cause this, since in my MVC 4 apps this problem does not occur.

Jason Evans
  • 28,906
  • 14
  • 90
  • 154
  • First you should indicate the name of your input to IsBoolValue , doig this this the value of input will be set by mvc, now model binding is not working, if you will indicate the name of input to be IsBoolValue model binding will work. – Nic Mar 04 '15 at 08:52

3 Answers3

56

I think I've figured it out.

I believe the Razor viewengine is adhering to the HTML 5 way of setting boolean attributes, as described here:

What does it mean in HTML 5 when an attribute is a boolean attribute?

In HTML 5, a bool attribute is set like this:

<input readonly />

or

<input readonly="readonly" />

So the Razor viewengine takes your model's bool value and will render (in my case) the value attribute if Model.IsBoolValue is true. Otherwise, if it's false then the value attribute is not rendered at all.

EDIT:

As mentioned Zabavsky in the comments, to force the value of True or False to appear in the value attrbiute, simple use ToString():

<input type="hidden" value="@Model.BoolProperty.ToString()" />

Community
  • 1
  • 1
Jason Evans
  • 28,906
  • 14
  • 90
  • 154
  • 19
    I think it's worth mentioning that the solution to this is simply call `ToString()` on the property: `value="@Model.IsBoolValue.ToString()"`. – Zabavsky Mar 04 '15 at 12:50
1
<div class="field_warp_hidden">
    <input type="checkbox" asp-for="ShowGoogleCaptcha" checked="@Model.ShowGoogleCaptcha" value="@Model.ShowGoogleCaptcha"/>
</div>

can set field_wrap_hidden is display:none;

checked and value must be set

1

I was using the hidden field in a partial view and I got an error when I used .ToString() alternative option was to specify the value property explicitly even after specifying asp-for

<input type="hidden" value="@Model.TargetmarketsToChangeAvailability[i].Available" asp-for="TargetmarketsToChangeAvailability[i].Available" />
Ajay Bhasy
  • 1,920
  • 1
  • 26
  • 38