Skip to content
This repository has been archived by the owner on Dec 14, 2018. It is now read-only.

Exception thrown when attempting to use model members in sections in a Razor Page #6294

Closed
DamianEdwards opened this issue May 18, 2017 · 4 comments

Comments

@DamianEdwards
Copy link
Member

DamianEdwards commented May 18, 2017

Repro

  1. Create a new Razor Pages project in Visual Studio
  2. Open the Index.cshtml.cs model class file
  3. Add a property to be accessed from the page's CSHTML file: public string Message { get; set; } = "Hello";
  4. Open the Index.cshtml page file
  5. Attempt to render the value of Model.Message inside the "Scripts" section:
    @section Scripts {
       <h1>@Model.Message</h1>
    }

Expected Result

The message is rendered in the HTML OK.

Actual Result

InvalidCastException: Unable to cast object of type 'Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary`1[System.Object]' to type 'Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary`1[WebApplication26.Pages.IndexModel]'.

@rynowak @NTaylorMullen

@Eilon
Copy link
Member

Eilon commented May 18, 2017

@rynowak - please reassign as appropriate.

@rynowak
Copy link
Member

rynowak commented May 19, 2017

Razor generates a property like the following. Code here

public ViewDataDictionary<TModel> ViewData => (ViewDataDictionary<TModel>)PageContext?.ViewData;

It's this cast operation that's blowing up.

When we're executing the Layout, we'll set ViewContext.ViewData here to the appropriate type for the Layout page, which will be ViewDataDictionary<object>.

I'm not sure why it's the same ViewContext. We should be providing a different ViewContext to the Layout.

@rynowak
Copy link
Member

rynowak commented May 23, 2017

#6310 will accomplish the bulk of what we need to do. I'll do a follow up afterwards to add a test

rynowak added a commit that referenced this issue May 24, 2017
This case was fixed by 2992f8e - this commit just adds a test to verify
the fix.
rynowak added a commit that referenced this issue May 24, 2017
This case was fixed by 2992f8e - this commit just adds a test to verify
the fix.
@rynowak
Copy link
Member

rynowak commented May 25, 2017

Fixed by: 2992f8e
Test Added: c1dd95b

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

3 participants