Aspnetcore.docs: Getting runtime error while displaying ViewData attribute value using @Model on view

Created on 10 Apr 2020  Â·  3Comments  Â·  Source: dotnet/AspNetCore.Docs

I am using _ViewData_ attribute to display its value on _View_ using _Model_.

Here is the code from my controller file:

` public class HomeController : Controller
{
[ViewData]
public string Title { get; set; }

    public ViewResult Index()
    {
        Title = "Home page title";

        return View();
    }
}`

Now as per the documentation , there are two ways to display this data on view file.

  1. We can display this data like below
    <h1>@ViewData["Title"]</h1>

Using this approach data gets displayed on view.

  1. We can display this data using Model and it gives an error:
    <h1>@Model.Title</h1>

Here is the error:

RuntimeBinderException: Cannot perform runtime binding on a null reference

And as per my understanding, this error is correct as we are not passing data as a Model.
second, suppose I am already using strongly type binding on view and along with this I want to use ViewData attribute. Now if I display the ViewData value using @ Model.Property then I will get compile-time error.

I find a similar issue here. This issue is closed without any valid answer. I believe this is a wrong explanation on the document. Kindly clarify.

Software versions

Asp.Net Core MVC 3.1


Document Details

⚠ Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

doc-bug

Most helpful comment

I've had a look into this, running up some examples and looking through the source. I get the same result as @nitishwebgentle, and it makes sense. I suggest we drop the @Model.Title example from the topic.

All 3 comments

I have tried with _Visual Studio 2019 & DotNet CLI_. In both the cases, I am getting the same error.

next time Can you create an issue from the doc page? That will connect the doc to the issue. Go to the bottom of the page and select This page .

image

I've had a look into this, running up some examples and looking through the source. I get the same result as @nitishwebgentle, and it makes sense. I suggest we drop the @Model.Title example from the topic.

Was this page helpful?
0 / 5 - 0 ratings