I have VS 2019 Pro and using .net 5 and C# 9. I created a project with ASP.NET Core Web App (without MVC) template. I got C0103 Error "The name 'ViewBag' does not exist in the current context." Here is an excerpt index.cshtml.cs code:
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Options;
using ARTS.Client_Models;
using ARTS.Models;
using repository;
:
:
public IActionResult OnGet()
{
this.VM = new home_VM(this._app_settings);
ViewBag.User = new User();
return Page();
}
I began to wonder if that is because I am not using MVC? If so, why?
Razor page doesn't support ViewBag, it requires external package Microsoft.AspNetCore.Mvc.ViewFeatures
. But ViewData is contained in Razor page, so it is a better way to replace it to ViewData.
ViewData["User"] = new User();
If you have to use ViewBag, you can refer to this answer.