Why is my hidden input writing: value="value" instead of true/false?

asp.netasp.net Mvc-4

asp.net Problem Overview


I have an MVC4 site, with (as part of a hidden form):

<input name="somefield" type="hidden" value="@ViewBag.Test"/>

The value of ViewBag.Test is true. The form field is posting to an input parameter of the form:

public ActionResult SomeAction(bool somefield = false, ...)

but somefield is always false. Upon investigating, I see that the source code has:

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

However, I know this used to work. What has happened, and what can I do?

asp.net Solutions


Solution 1 - asp.net

This behaviour changed between MVC3 and MVC4. In MVC3, if you have:

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

it would write very literally:

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

However, in MVC4, it follows the "checkbox" etc rules, so if the value is true you get:

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

and if it is false it is omitted completely:

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

To get around this, consider .ToString():

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

which then follows string rules rather than boolean rules.

Solution 2 - asp.net

initialized Boolean values bool something =false;

then convert this value into string like,

then we can read

    public ActionResult Somemethod(bool IsFromDB) => you can get Boolean value here 
    {
    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMarc GravellView Question on Stackoverflow
Solution 1 - asp.netMarc GravellView Answer on Stackoverflow
Solution 2 - asp.netNayansukh PatilView Answer on Stackoverflow