Working with boolean values and hidden fields in MVC 4

n
nnn
n

nHi guys,

n

n

n

nThis isnquite simple but I learned something new in MVC today, so thought to share with younall.

n

n

n

nI was tryingnto assign a Boolean field to a hidden field using ViewBag in MVC

n

n

n

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

n

n

n

nAnd nownwhen I was trying to read the value using jQuery it was always returning menhidden field’s value as “value” which was quite strange to me as I wasnexpecting true or false.

n

n

n

nvar hiddenVal = $(“#somehiddenfield”).val();

n

n

n

nAfter anquick search, came to know that this has been changed a little in MVC 4 , nownit follows the checkbox behavior.

n

ni.e. younwill get the hidden field’s value as “value” when the Boolean value will bentrue and nothing when Boolean value will be false.

n

n

n

nSo younmight need to change the implementation a little if you explicitly want to readnthe true and false as hidden field values from jQuery.

n

n

n

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

n

n

n

n

n n

n

nHope thisnhelps someone.

n

Leave a Comment