Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC 5 renders different bool value for hidden input

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.

like image 384
Jason Evans Avatar asked Mar 04 '15 08:03

Jason Evans


People also ask

How do I get the ViewBag value in a hidden field?

The ViewBag object value will be set inside Controller and then inside the View, the value will be assigned to the Hidden Field created using Html. Hidden helper function in ASP.Net MVC Razor.

What is HTML HiddenFor?

HiddenFor() is a strongly typed method that is bounded with model class. It communicates and send/receive value to model class properties. Generally it contains 2 parameters; Hidden Field Name which is a model property and Value for Hidden Field.


1 Answers

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()" />

like image 163
Jason Evans Avatar answered Sep 17 '22 14:09

Jason Evans