![](/img/trans.png)
[英]The model item passed into the dictionary is of type …, but this dictionary requires …
[英]model item passed into the dictionary is of type 'System.Boolean', but this dictionary requires a model item of type 'MyProject.checkboxstate'
我有一個自定義的html幫助器,最后一個參數為bool類型。 當數據庫中有數據時,我的代碼工作正常。 但是,沒有數據,它會拋出以下錯誤:
System.NullReferenceException:未將對象引用設置為對象的實例。
然后,我試圖檢查可能的“空值”並將值作為“假”發送到視圖,顯然,沒有成功。
public ActionResult Index()
{
bool? defaultVal = true;
var dbValue = context.checkboxstates.Where(c => c.Name == "Country").FirstOrDefault();
if (dbValue == null)
{
return View(defaultVal);
}
return View(dbValue);
}
我的觀點:
@model MyProject.CheckboxState
@Html.MyCustomHtmlHelper("text", "AnotherText", "changeState", Model.state)
在這里,Model.state負責根據數據庫返回的值“檢查”復選框“已檢查”或“未選中”。 我沒有模型,因為我正在使用數據庫第一種方法。
如果我嘗試從控制器顯式傳遞一個布爾值,我收到此錯誤消息:
傳遞到字典中的模型項的類型為“System.Boolean”,但此字典需要“MyProject.checkboxstate”類型的模型項。
如果Model
為null
嘗試將默認值傳遞給自定義html幫助器:
@Html.MyCustomHtmlHelper("text", "AnotherText", "changeState", Model!=null?Model.state:false)
您不能將布爾參數傳遞給視圖,因為它期望將CheckboxState
類型的對象作為模型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.