Passing boolean data into a partial view and using it to conditionally display a class
Hi all, many thanks in advance for your help.
In my template view:
@Html.Partial("HeaderSearchForm", new ViewDataDictionary {{"isExpandable", true}})
In my HeaderSearchForm.cshtml
@{
var isExpandableValue = (bool)ViewData["isExpandable"];
var isExpandable = (isExpandableValue) ? "-form expandable-search" : "";
}
I'm getting a nullreference error on line 5
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 3: @{
Line 4: var thing = (bool)ViewData["isExpandable"];
Line 5: var isExpandable = (thing) ? "-form expandable-search" : "";
Line 6: }
Line 7:
Source File: c:\inetpub\wwwroot\mhshomes\Views\Partials\HeaderSearchForm.cshtml Line: 5
Strange, then it should work, assuming you haven't made any typos. I can't see any reason for it not working!
But you could try an alternative approach of passing a model to your partial view that has one boolean field. It's a little neater, but requires a bit more code. So you'd need to create a class, similar to:
public class SearchConfigModel
{
public bool IsExpandable { get; set; }
}
Then pass it to your partial:
@Html.Partial("HeaderSearchForm", new SearchConfigModel() { IsExpandable = true } })
Then make your partial inherit from UmbracoViewPage:
@inherits UmbracoViewPage<SearchConfig>
You can then access Model.IsExpendable in your partial view.
Passing boolean data into a partial view and using it to conditionally display a class
Hi all, many thanks in advance for your help.
In my template view:
In my HeaderSearchForm.cshtml
I'm getting a nullreference error on line 5
Here's the html for reference:
Currently migrating the platform to MVC views, learning Umbraco and seeing the end of the tunnel. Exciting times.
What does your HeaderSearchForm partial inherit from? It needs to inherit from
UmbracoTemplatePage
for ViewData to be available, I believe.Thanks for your reply Dan,
I do have this at the top of the file
Strange, then it should work, assuming you haven't made any typos. I can't see any reason for it not working!
But you could try an alternative approach of passing a model to your partial view that has one boolean field. It's a little neater, but requires a bit more code. So you'd need to create a class, similar to:
Then pass it to your partial:
Then make your partial inherit from UmbracoViewPage:
You can then access
Model.IsExpendable
in your partial view.A belated answer, but I got the same problem and found the answer. I thought I'd share it here.
The default call to a partial:
passes the current model to the partial. You used:
This however does not pass the model, only the ViewDataDictionary. So to pass them both you need to use a different overload of Html.Partial:
is working on a reply...