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?

1

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

3

Html attributes requires string objects It's not automatically converted

So you have to use ToString()

Comments

-1

Please try this.

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

1 Comment

this syntax is used for check box control when bind boolean value through jquery.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.