haiqing
haiqing

Reputation: 23

Boolean model binding issue in Mvc 4

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?

Upvotes: 2

Views: 7668

Answers (3)

Manoj Gupta
Manoj Gupta

Reputation: 474

Please try this.

 $('#controlId').is(":checked");

Upvotes: -1

Martin Liversage
Martin Liversage

Reputation: 106926

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.

Upvotes: 3

Joan Caron
Joan Caron

Reputation: 1970

Html attributes requires string objects It's not automatically converted

So you have to use ToString()

Upvotes: 3

Related Questions