[英]Switch on Nullable Boolean : case goes to null when value is true
[英]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
這就可以正常工作。 但是如果值為null,則會出現以下錯誤:
傳遞到字典中的模型項的類型為'System.Data.Entity.DynamicProxies.MyAwesomeModel_EB6A12E11ECADA2C6B22289ACDF73813854383896F2E78956FDFFE6225F0404F',但此字典需要類型為'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
的partial時,默認情況下它會在主視圖中使用模型,所以在你的情況下它的傳遞和MyAwesomeModel
實例到一個期望模型是bool?
的視圖bool?
(因此錯誤)。
如果屬性的值為null
則需要有條件地傳遞新的ViewDataDictionary
@{ Html.RenderPartial("_Checkbox", Model.SomeNullableBoolean.HasValue ?
new ViewDataDictionary(){ Model = Model.SomeNullableBoolean } :
new ViewDataDictionary()); }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.