user9993
user9993

Reputation: 6170

How do I use strongly typed models and @model?

I'm learning ASP.NET MVC. I have a service folder where I have a class which reads data from an XML file. 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. 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. 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>

Upvotes: 0

Views: 248

Answers (1)

V-SHY
V-SHY

Reputation: 4125

Refer to @Erik Funkenbusch explanation of MVC @model meaning

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.

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).

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.

And have some idea here

Upvotes: 3

Related Questions