I have a custom html helper with the last parameter as bool type. My code works fine when there is data in the database. But, without data, it throws following error:
System.NullReferenceException: Object reference not set to an instance of an object.
Then, I tried to check for the possible 'null value' and send the value as 'false' to the view, apparently, without success.
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);
}
My View:
@model MyProject.CheckboxState
@Html.MyCustomHtmlHelper("text", "AnotherText", "changeState", Model.state)
Here, Model.state is responsible for 'checking' checkbox 'checked' or 'unchecked' based upon the value returned from database. I do not have a model as I'm using database first approach.
If I try to pass explicitly a boolean value from the controller, I get this error message:
The model item passed into the dictionary is of type 'System.Boolean', but this dictionary requires a model item of type 'MyProject.checkboxstate'.
In case Model
is null
try passing a default value to your custom html helper:
@Html.MyCustomHtmlHelper("text", "AnotherText", "changeState", Model!=null?Model.state:false)
You can't pass a boolean parameter to your view due to it's expecting an object of CheckboxState
type as model.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.