当值为 null 时,将可空布尔值传递给部分视图不起作用
Pass nullable boolean to partial view not working when value is null
我正尝试在我的剃刀视图中执行此操作:
@{ Html.RenderPartial("_Checkbox", Model.SomeNullableBoolean); }
_Checkbox.cshtml:
@model bool?
@if (Model == null)
{
Some code
}
else if (Model == true)
{
Some other code
}
只要 Model.SomeNullableBoolean
设置为 true
或 false
,这就可以正常工作。
但如果该值为空,我会收到以下错误:
The model item passed into the dictionary is of type
'System.Data.Entity.DynamicProxies.MyAwesomeModel_EB6A12E11ECADA2C6B22289ACDF73813854383896F2E78956FDFFE6225F0404F',
but this dictionary requires a model item of type
'System.Nullable`1[System.Boolean]'.
模型(MyAwesomeModel
)中的可空属性定义如下:
public bool? SomeNullableBoolean { get; set; }
我应该如何进一步调查这个问题?
我听从了 Stephen Muecke 的建议并采用了 ViewDataDictionary
方法:
@{ Html.RenderPartial("_Checkbox", null, new ViewDataDictionary { { "BoolValue", Model.SomeNullableBoolean}}); }
_Checkbox.cshtml:
@{
var theValue = (bool?) ViewData["BoolValue"];
}
@if (theValue == null)
{
something
}
else if (theValue == true)
{
something
}
else
{
something
}
这非常有效!
当您将模型传递给 null
的部分时,默认情况下它将在主视图中使用该模型,因此在您的情况下,它将 MyAwesomeModel
的传递和实例传递给视图期望模型为 bool?
(因此出现错误)。
如果 属性 的值为 null
,则需要有条件地传递一个新的 ViewDataDictionary
@{ Html.RenderPartial("_Checkbox", Model.SomeNullableBoolean.HasValue ?
new ViewDataDictionary(){ Model = Model.SomeNullableBoolean } :
new ViewDataDictionary()); }
我正尝试在我的剃刀视图中执行此操作:
@{ Html.RenderPartial("_Checkbox", Model.SomeNullableBoolean); }
_Checkbox.cshtml:
@model bool?
@if (Model == null)
{
Some code
}
else if (Model == true)
{
Some other code
}
只要 Model.SomeNullableBoolean
设置为 true
或 false
,这就可以正常工作。
但如果该值为空,我会收到以下错误:
The model item passed into the dictionary is of type 'System.Data.Entity.DynamicProxies.MyAwesomeModel_EB6A12E11ECADA2C6B22289ACDF73813854383896F2E78956FDFFE6225F0404F', but this dictionary requires a model item of type 'System.Nullable`1[System.Boolean]'.
模型(MyAwesomeModel
)中的可空属性定义如下:
public bool? SomeNullableBoolean { get; set; }
我应该如何进一步调查这个问题?
我听从了 Stephen Muecke 的建议并采用了 ViewDataDictionary
方法:
@{ Html.RenderPartial("_Checkbox", null, new ViewDataDictionary { { "BoolValue", Model.SomeNullableBoolean}}); }
_Checkbox.cshtml:
@{
var theValue = (bool?) ViewData["BoolValue"];
}
@if (theValue == null)
{
something
}
else if (theValue == true)
{
something
}
else
{
something
}
这非常有效!
当您将模型传递给 null
的部分时,默认情况下它将在主视图中使用该模型,因此在您的情况下,它将 MyAwesomeModel
的传递和实例传递给视图期望模型为 bool?
(因此出现错误)。
如果 属性 的值为 null
ViewDataDictionary
@{ Html.RenderPartial("_Checkbox", Model.SomeNullableBoolean.HasValue ?
new ViewDataDictionary(){ Model = Model.SomeNullableBoolean } :
new ViewDataDictionary()); }