简体   繁体   English

当value为null时,将nullable boolean传递给部分视图不起作用

[英]Pass nullable boolean to partial view not working when value is null

I'm trying to do this in my razor view: 我想在剃须刀视图中这样做:

@{ Html.RenderPartial("_Checkbox", Model.SomeNullableBoolean); }

_Checkbox.cshtml: _Checkbox.cshtml:

@model bool?

@if (Model == null)
{
    Some code
}
else if (Model == true)
{
    Some other code
}

This works fine as long as the Model.SomeNullableBoolean is set to either true or false . 只要将Model.SomeNullableBoolean设置为truefalse这就可以正常工作。 But if the value is null I get the following error: 但是如果值为null,则会出现以下错误:

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]'. 传递到字典中的模型项的类型为'System.Data.Entity.DynamicProxies.MyAwesomeModel_EB6A12E11ECADA2C6B22289ACDF73813854383896F2E78956FDFFE6225F0404F',但此字典需要类型为'System.Nullable`1 [System.Boolean]'的模型项。

The nullable property inside the model ( MyAwesomeModel ) is defined like this: 模型中的可空属性( MyAwesomeModel )定义如下:

public bool? SomeNullableBoolean { get; set; }

Any ideas how I should investigate this further? 有什么想法我应该如何进一步调查这个?

I followed Stephen Muecke's advice and went with the ViewDataDictionary approach: 我遵循了Stephen Muecke的建议并采用了ViewDataDictionary方法:

@{ Html.RenderPartial("_Checkbox", null, new ViewDataDictionary { { "BoolValue", Model.SomeNullableBoolean}}); }

_Checkbox.cshtml: _Checkbox.cshtml:

@{
    var theValue = (bool?) ViewData["BoolValue"];
}

@if (theValue == null)
{
    something
}
else if (theValue == true)
{
    something
}
else
{
    something
}

This works perfectly! 这很完美!

When you pass a model to a partial which is null , by default it will use the model in the main view, so in your case its passing and instance of MyAwesomeModel to a view that expects a model which is bool? 当你将模型传递给null的partial时,默认情况下它会在主视图中使用模型,所以在你的情况下它的传递和MyAwesomeModel实例到一个期望模型是bool?的视图bool? (hence the error). (因此错误)。

You need to conditionally pass a new ViewDataDictionary if the value of the property is null 如果属性的值为null则需要有条件地传递新的ViewDataDictionary

@{ Html.RenderPartial("_Checkbox", Model.SomeNullableBoolean.HasValue ?
    new ViewDataDictionary(){ Model = Model.SomeNullableBoolean } : 
    new ViewDataDictionary()); }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM