Szymon Kądziołka
Szymon Kądziołka

Reputation: 55

ASP.NET Can't reference model from my view

I have a problem that I can't reference my model Samochody from view Index i've created. I created this model in folder called Models and all should work but it looks like i'm not as smart as i thought :D Can you guys help me with this? Here's the code

Samochody.cs model:

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using static WebApplication2.Models.Samochody;

namespace WebApplication2.Models
{
    public class Samochody
   {
    public class Car
    {
        public int Id { get; set; }
        public string Brand { get; set; }
        public string Model { get; set; }
        public decimal Price { get; set; }
        public DateTime Bought { get; set; }
        public DateTime Sold { get; set; }
    }

}

public class CarDBCtxt : DbContext
{
    public DbSet<Car> Cars { get; set; }
}

}

And Index.cshtml

@model Samochody.Models.Car //error here, can't find Samochody
@{
   Layout = null;
}

<!DOCTYPE html>

<html>
<head>
   <meta name="viewport" content="width=device-width" />
   <title>Index</title>
</head>
<body>

<div>

</div>
</body>
</html>

This is second time i have this type of error and it's from 2 different tutorials.

Upvotes: 1

Views: 3244

Answers (1)

Rocklan
Rocklan

Reputation: 8130

You're missing the namespace of your class in your index.cshtml. So it needs to be:

@model WebApplication2.Models.Samochody.Models.Car

or an alternative is to edit the web.config file in the Views folder and add the namespace there:

<system.web.webPages.razor>
  <host ...
  <pages ...
   <namespaces>
     <add ...
     <add namespace="WebApplication2.Models" />

and then you won't need to add the namespace within each .cshtml file.

Upvotes: 1

Related Questions