質問

I've got an editor template that is applied to several data types. Most of them are displayed by TextBoxFor, but I'd like to use CheckBoxFor on the booleans (these are not nullable). As it is now:

if (data.DataTypeName == "Boolean")
{
    @Html.CheckBoxFor(m => m, new { @class = classData })
}
else
{
    @Html.TextBoxFor(m => m, new { @class = classData })
}

I get an error in CheckBoxFor lambda: Cannot implicitly convert type 'object' to 'bool'. An explicit conversion exists (are you missing a cast?). If I try the cast, I get an exception just like this: ASP.net MVC CheckBoxFor casting error. I can't use that solution, however, because I can't use the model member on this generalized solution. Am I going to have to give up the dream?

役に立ちましたか?

解決

So your property is object type and you need to at runtime determine the editor for that type? If that's the case don't use the *For methods and explicitly cast and pass the value:

if (data.DataTypeName == "Boolean")
{
    @Html.CheckBox("", (bool)Model, new { @class = classData })
} 
else
{
    @Html.TextBox("", (string)Model, new { @class = classData })
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top