2

I want to bind a boolean property to a hidden input controller, but the output html code was error

code as follows:

public class TestModel
{
    public bool IsOk { get; set; }
    public bool IsSuccess { get; set; }
}

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new TestModel { IsOk = false, IsSuccess = true });
    }
}

<h2>Index</h2>
<p>@Model.IsOk</p>
<p>
  <input type="hidden" value="@Model.IsOk" />
</p>
<p>
  <input type="hidden" value="@Model.IsSuccess" />
</p>

Html Output

<h2>Index</h2>
<p>False</p> //works

<p>
    <input type="hidden" /> //where is value?
</p>

<p>
    <input type="hidden" value="value" /> //wath's this?
</p>

But if i use ToString(), all above works well, so is it my mistake?

haiqing
  • 23
  • 1
  • 3
  • 4
    possible duplicate of [Why is my hidden input writing: value="value" instead of true/false?](http://stackoverflow.com/questions/13455270/why-is-my-hidden-input-writing-value-value-instead-of-true-false) – nemesv Aug 30 '13 at 09:13

3 Answers3

3

Html attributes requires string objects It's not automatically converted

So you have to use ToString()

Joan Caron
  • 1,969
  • 18
  • 21
3

In HTML when you have an attribute which functions as an on/off or true/false switch you remove the attribute when the attribute is off/false and add the attribute with the same value as the attribute name when the attribute is on/true. Razor provides you with that functionality as you have already experienced.

Perhaps you intend to use Html.HiddenFor in the view?

<p>
    @Html.HiddenFor(m => m.IsOk)
</p>
<p>
    @Html.HiddenFor(m => m.IsSuccess)
</p>

This will produce this HTML where you have value="False" and value="True" as you expect:

<p>
    <input data-val="true" data-val-required="The IsOk field is required." 
        id="IsOk" name="IsOk" type="hidden" value="False" />
</p>
<p>
    <input data-val="true" data-val-required="The IsSuccess field is required."
        id="IsSuccess" name="IsSuccess" type="hidden" value="True" />
</p>

Also, the model binder will be able to round-trip you view model properties.

Martin Liversage
  • 104,481
  • 22
  • 209
  • 256
-1

Please try this.

 $('#controlId').is(":checked");
Alex
  • 8,461
  • 6
  • 37
  • 49
Manoj Gupta
  • 456
  • 4
  • 9