Pages

Thursday, December 5, 2013

Working with boolean values and hidden fields in MVC 4



Hi guys,

This is quite simple but I learned something new in MVC today, so thought to share with you all.

I was trying to assign a Boolean field to a hidden field using ViewBag in MVC

<input type="hidden" id="somehiddenfield" value="@ViewBag.MyBooleanValue" />

And now when I was trying to read the value using jQuery it was always returning me hidden field’s value as “value” which was quite strange to me as I was expecting true or false.

var hiddenVal = $("#somehiddenfield").val();

After a quick search, came to know that this has been changed a little in MVC 4 , now it follows the checkbox behavior.
i.e. you will get the hidden field’s value as “value” when the Boolean value will be true and nothing when Boolean value will be false.

So you might need to change the implementation a little if you explicitly want to read the true and false as hidden field values from jQuery.

<input type="hidden" id="somehiddenfield " value="@(ViewBag.MyBooleanValue.ToString())" />

 
Hope this helps someone.

No comments:

Post a Comment