user3495847
user3495847

Reputation:

ASP.Net core model not found in view

I'm going over some ASP.Net core tutorials. I'm working with models. I've created a Quote model to store a name and some text to a DB but I am getting the error:

obj/Debug/netcoreapp2.1/Razor/Views/Home/CreateQuote.g.cshtml.cs(23,92): error CS0246: The type or namespace name 'Quotes' could not be found.

HomeController.cs

using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using DbConnection;
using Session.Models;

namespace Session.Controllers
{
    public class HomeController : Controller
    {
        [HttpGet("quote")]
        public IActionResult CreateQuote() {
            return View();
        }

        [HttpPost("quote/Create")]
        public void Create(Quotes quote) {
            System.Console.WriteLine("Hi!!!!");
            System.Console.WriteLine("name is: "+quote.name);
        }

        [HttpGet("test")]
        public IActionResult test(Quotes obj) {
            ViewBag.name = obj.name;
            ViewBag.quote = obj.quote;

            System.Console.WriteLine(obj.name);
            System.Console.WriteLine(obj.quote);
            return View("test");
        }    
    }
}

Quotes.cs

using System;
using System.ComponentModel.DataAnnotations;

namespace Session.Models
{
    public class Quotes
    {
        //[Required]
        [Display(Name = "Your Name:")]
        public string name {get;set;}

        //[Required]
        [Display(Name = "Quote:")]
        public string quote{get;set;}
        public DateTime createdAt {get;set;}
    }
}

CreateQuote.cshtml

@model Quotes
<form asp-action="Create" asp-controller="Home" method="post">
    <span asp-validation-for="name"></span>
    <label asp-for="name"></label>
    <input asp-for="name"><br>
    <span asp-validation-for="quote"></span>
    <label asp-for="quote"></label>
    <input asp-for="quote"><br>
    <input value="Add Quote" type="submit">
 </form>

Upvotes: 6

Views: 7212

Answers (3)

Honza P.
Honza P.

Reputation: 1242

Option 4 - see analysis in enter link description here for me this helped as the referenced project was of Windows Application type :-/. 3 hours wasted ... changed it to Class Library.

Upvotes: 0

Erik Philips
Erik Philips

Reputation: 54676

Option 3 - ViewImports

_ViewImports.cshtml

@using Session.Models

Upvotes: 3

Floor
Floor

Reputation: 216

Option 1

Refer to your model as @model Session.Models.Quotes in your CreateQuote.cshtml view.

Option 2

@model Quotes
@using Session.Models

Upvotes: 1

Related Questions