I am trying to do a ContainsKey check for a field in a razor view that is sometimes not present. Even when I have the ContainsKey if statement in my code I get the The given key was not present in the dictionary error. There are two fields (keys) that are not mandatory in the schemas but when the page loads and they are null it breaks. This is inside of a foreach loop. I am using VS to debug and when I set a breakpoint I can see the keys does not exist in the MetadataFields["userAgentCollection"].EmbeddedValues collections for some nodes. The code is posted below.
@model DD4T.ContentModel.IPage
<span># Modified </span> @Model.MetadataFields["modifiedDate"].Value<br /><br />
@foreach(var userAgent in @Model.MetadataFields["userAgentCollection"].EmbeddedValues)
{
<span>User Agent: </span>@userAgent["userAgent"].Value
if (userAgent.ContainsKey("disallow"))
{
foreach (var disallow in @userAgent["disallow"].EmbeddedValues)
{
if (disallow["Disallow"].Value != "")
{
<br />@disallow["Disallow"].Value
}
}
}
if (userAgent.ContainsKey("crawlDelay"))
{
<br /><span>Crawl Delay: </span>@userAgent["crawlDelay"].Value
}
<br /><br />
}
<span>Sitemap: </span>@Model.MetadataFields["sitemap"].Value<br />