简体   繁体   English

如何使用强类型模型和@model?

[英]How do I use strongly typed models and @model?

I'm learning ASP.NET MVC. 我正在学习ASP.NET MVC。 I have a service folder where I have a class which reads data from an XML file. 我有一个服务文件夹,其中有一个用于从XML文件读取数据的类。 I've created a controller that I think (?) should work, and I'm attempting to create a view for this as well but for some reason I can't get intellisense to autocomplete the @model which makes me think I've done something wrong. 我已经创建了一个我认为(?)应该可以工作的控制器,并且我也试图为此创建一个视图,但是由于某种原因,我无法智能地自动完成@model,这使我认为我已经做错了什么。 Additionally, when I try access model properties from the view (eg Model.Description - if that is even the syntax?) I get numerous missing { and } errors. 另外,当我尝试从视图访问模型属性时(例如Model.Description甚至是语法?),我会遇到许多丢失的{和}错误。 What am I doing wrong? 我究竟做错了什么?

Controller: 控制器:

public ActionResult Index()
{
    NewsReader newsReader = new NewsReader(); //Read news from file
    var newsItems = newsReader.GetNewsItems();

    return View(newsItems);
}

And so far this is all I have for the view: 到目前为止,这就是我的观点:

@Model IEnumerable<TestSite.Services.News.NewsItem>

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title></title>
</head>
<body>
    <div>
        <ul>
            @foreach(Model.Description)
            {

            }
        </ul>
    </div>
</body>
</html>

Refer to @Erik Funkenbusch explanation of MVC @model meaning 请参阅MVC @model含义的 @Erik Funkenbusch解释

The @ sign is a directive to tell the Razor engine that what follows is code, and it should compile that rather than simply write it to the output. @符号是一个指令,用于告诉Razor引擎其后是代码,它应该编译而不是简单地将其写入输出。

so when you type 所以当你输入

@model blah This is compiled by razor, and tells the Razor engine that the type of the model is 'blah', so that when you use the keyword Model (note the capital M and you would have to use the @ sign as well) it will refer to the model you have defined (in this case blah). @model blah这是由razor编译的,并告诉Razor引擎该模型的类型为'blah',因此,当您使用关键字Model时(请注意,使用大写字母M时,还必须使用@符号)它将引用您已定义的模型(在本例中为blah)。

Therefore corrections should be taken as following: 因此,应采取以下纠正措施:

//@Model IEnumerable<TestSite.Services.News.NewsItem>
@model IEnumerable<TestSite.Services.News.NewsItem>


//@foreach(Model.Description)
@foreach(var item in model.Description)
{
}

I recommend you to read Getting Started with ASP.NET MVC 5 to learn some basics about ASP.NET MVC 5. Razor engine is used by MVC 5 for the view styling. 我建议您阅读ASP.NET MVC 5入门,以了解有关ASP.NET MVC 5的一些基础知识。MVC 5使用Razor引擎进行视图样式设置。

And have some idea here 并在这里有一些想法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM