user6745503
user6745503

Reputation:

model item passed into the dictionary is of type 'System.Boolean', but this dictionary requires a model item of type 'MyProject.checkboxstate'

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'.

Upvotes: 1

Views: 384

Answers (1)

ocuenca
ocuenca

Reputation: 39326

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.

Upvotes: 0

Related Questions