Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
745 views
in Technique[技术] by (71.8m points)

asp.net mvc - different between @Model and @model

Basically I'm doing a test caused by one of excpetion.

By using return View(list_a) in controller I passed a list into my view, On my View page, the code is like:

@{
    ViewBag.Title = "KYC_Home";
}
@using UniBlue.Models;
@model UniBlue.Models.KYC
...
@foreach(KYC a in Model)
...

there will be an exception says:

CS1579: foreach statement cannot operate on variables of type 'UniBlue.Models.KYC' because 'UniBlue.Models.KYC' does not contain a public definition for 'GetEnumerator'

But, when i changed my code to @Model Page looks good but on the title it shows:

System.Collections.Generic.List`1[UniBlue.Models.KYC] UniBlue.Models.KYC

as regular HTML text

Can anybody tell me why this happened? What should I do to remove the strange title line?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

One is used to declare the strong type that the model is, and the other is used to access the model itself.

The following says that the strong type used for the model is UniBlue.Models.KYC.

@model UniBlue.Models.KYC

This basically declares the 'variable' Model as that type. It's akin to doing the following:

UniBlue.Models.KYC Model;

Model is a variable, @model is a keyword saying what type Model will be.

Your error is because you've declared Model as KYC, but KYC is not enumerable. You're using it in a foreach expecting an IEnumerable<UniBlue.Models.KYC> which is not the case.

If your model is truly a list, then use

@model IEnumerable<UniBlue.Models.KYC>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...