문제

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