Mvc: Updates to ViewData from a _ViewStart for a Razor Page behave wierdly

Created on 27 Feb 2018  路  7Comments  路  Source: aspnet/Mvc

This is an inconsistency between views and pages, and results in ViewData doing wierd broken when used in a _ViewStart and in a Page.

Repro:

  1. Open Mvc.NoFun.sln
  2. Write the following the MvcSandbox/Pages/_ViewStart.cshtml
@{ 
    Layout = "_Layout";
    ViewData["Title"] = "ViewStart " + ViewData["Title"];
}
  1. Write the following the MvcSandbox/Pages/_ViewStart.cshtml
@{
    ViewData["Title"] = ViewData["Title"] + "From Page";
}
  1. Run MvcSandbox and navigate to /PagesHome

The title will be ViewStart - MvcSandbox instead of what you'd expect ViewStart From Page - MvcSandbox.

If you debug, you'll see that the execution order is correct, but the viewdata isn't getting shuttled around correctly. It looks roughly like this:

  1. _ViewStart runs - sets the title
  2. PagesHome runs - can't see the title from 1), sets a title also
  3. Layout runs - reads the title, sees the title from 1)

The result that you'd get if you built the same setup using Views is as expected. The execution order is the same, but the all operate on the same data

1 - Ready bug

All 7 comments

/cc @shanselman FYI

So to be clear, this works in the right order in MVC Views but not in Razor Pages, right? So the ViewData is somehow a different instance between the two?

@shanselman you mean "in views but not in pages", as they're both MVC

Gotcha. Edited. Which is why this is weird as it's all "the same thing."

Same thing, with conditional logic depending on the path taken.

So the ViewData is somehow a different instance between the two?

Yup. Pages have some magic for ViewData that do some extra things, but it apparently has a bug.

Dup of https://github.com/aspnet/Mvc/issues/7675. Using the newer issue since it's already assigned to me.

Was this page helpful?
0 / 5 - 0 ratings