Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ViewModel Not Being Recognized by MVC 6 in Visual Studio Code

I created a ViewModel called AddNewInventoryViewModel (Project is ASP.NET MVC using Visual Studio Code on OSX with the runtime .NET Core 5.0) and added it into the ViewModel models folder, so that I have the structure:

ViewModels/Home/AddNewInventoryViewModel.cs
Views/Home/AddNewInventory.cshtml

My view looked like this:

@model AddNewInventoryViewModel
...Content here

My Home controller action method looked like this:

[HttpGet]
public IActionResult AddNewInventory()
{
    return View();    
}

For sake of brevity, I won't include the ViewModel.cs file itself.

However, when I visited the page in my app (AddNewInventory.cshtml), I received the error:

DNXCore,Version=v5.0 error CS0246: The type or namespace 
'AddNewInventoryViewModel' could not be found (are you missing a using directive or an assembly reference?)

Why the error? What am I missing?

like image 217
joshmcode Avatar asked Apr 03 '16 00:04

joshmcode


People also ask

What is ViewModel in MVC C#?

ViewModel = Model that is created to serve the view. ASP.NET MVC view can't have more than one model so if we need to display properties from more than one model in the view, it is not possible. ViewModel serves this purpose. View Model is a model class that can hold only those properties that are required for a view.

How do I write C# code in a view .cshtml file?

Go to solution explorer => Views Folder => Right-click on “Home” Folder >> go to “Add” >> Click on [New Item] as follow. Select MVC 5 View Page with Layout(Razor) from "Add New Item" window and provide the required name like "ViewPageWithLayout. cshtml" click on "Add" button as follow.


1 Answers

The reason I was getting this error is that I failed to add a reference in the _ViewImports.cshtml in the Views folder. For example, below I was missing the project.ViewModels.Home reference.

@using project
@using project.Models
@using project.ViewModels.Account
@using project.ViewModels.Manage
@using project.ViewModels.Home
@using Microsoft.AspNet.Identity
@addTagHelper "*, Microsoft.AspNet.Mvc.TagHelpers"

One I added that, everything worked fine.

like image 62
joshmcode Avatar answered Sep 28 '22 05:09

joshmcode