Jesse
Jesse

Reputation: 8393

View generating error message: String was not recognized as a valid Boolean

Within an admin page I originally was generating several checkboxes within a view as per below:

Model:

public class Foo
{
    public const string Bar = "SomeString";
}

View:

@Html.CheckBox(Foo.Bar)
@Html.Label(Foo.Bar)

However, I wanted to change the display name of several of the checkboxes, so I created a view model (to later add a display name attribute):

public class FooViewModel
{
     public string Bar
     {
         get { return Foo.Bar; }
     }
}

And modified the view:

@Html.CheckBox(Model.Bar)
@Html.LabelFor(m => m.Bar)

However, the view is now generating an error when rendering the checkbox:

String was not recognized as a valid Boolean

Note, that if I change the property name within the view model to anything other than "Bar" the view is rendered correct. EG:

public class FooViewModel
{
     public string WTF
     {
         get { return Foo.Bar; }
     }
}

@Html.CheckBox(Model.WTF)
@Html.LabelFor(m => m.WTF)

Can anybody explain to me why this error is occurring if my viewmodel property is named "Bar"?

Edit: I have updated my question slightly seeing as how, i'm generating some confusion. The view is used as a search form and the checkboxes are simply used for selecting "search critera".

I'm generating the checkbox in this fashion so the name / id of the checkbox is related to corresponding business logic within the controller.

I'm aware that code will not compile if property name / field name within the same class are identical. That is not the issue, as i'm simply initializing a property from constant within a different namespace.

Upvotes: 3

Views: 4822

Answers (2)

Jesse
Jesse

Reputation: 8393

Using a different checkbox constructor resolves the issue:

@Html.CheckBox(Model.Bar, false)
@Html.LabelFor(m => m.Bar)

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038930

You cannot have a constant called Bar and a property called Bar:

public class Foo
{
    public const string Bar = "SomeString";

    public string Bar
    {
        get { return Foo.Bar; }
    }
}

This particular code snippet is invalid C# and won't even compile.

This being said the CheckBox/CheckBoxFor helpers in ASP.NET MVC work with boolean values. So I really don't understand why are you even attempting to bind it to a string property and the purpose of this Bar string constant.

The correct would be to have the following view model:

public class MyViewModel
{
    [Display(Name = "som estring")]
    public bool MyBoolValue { get; set; }
}

and in the strongly typed view:

@Html.LabelFor(x => x.MyBoolValue)
@Html.CheckBoxFor(x => x.MyBoolValue)

Upvotes: 1

Related Questions