StillLearnin
StillLearnin

Reputation: 1499

ASP.NET Page ViewData Overwritten (missing)

Contents of _ViewStart.cshtml

@{
    Layout = "_Layout";
    ViewData["IndexLink"] = Context.Request.Path != "/" ? "/Index" : "";
}

Contents of Downloads.cshtml

@page
@model DownloadsModel
@{
    ViewData["Title"] = "Downloads";
}

Snippet from _Layout.cshtml

<title>@ViewData["Title"] - ABC Sofware LLC</title>

Problem:

The <title> tag is being rendered without the view's title.

Troubleshooting Steps:

I put a break point in _Layout.cshtml to see what ViewData contains. It has one key instead of two.

@ViewData.Keys
    Count = 1
    [0]: "IndexLink"

If I remove the ViewData["IndexLink"] line from _ViewStart.cshtml then ViewData["Title"] is set.

@ViewData.Keys
    Count = 1
    [0]: "Title"

Why does setting a ViewData key in _ViewStart.html break ViewData in the views?

Upvotes: 1

Views: 482

Answers (1)

Mike Thibault
Mike Thibault

Reputation: 213

Looks like this is currently a bug (see https://github.com/aspnet/Mvc/issues/7675 -- planned to be fixed in Core 2.2.0) but the current workaround is instead of:

ViewData["Key"]

you would use

ViewContext.ViewData["Key"]

in both _ViewStart.cshtml and Downloads.cshtml. Referencing

@ViewData["Key"]

in _Layout.cshtml still seems to work fine for me.

Upvotes: 4

Related Questions