Html 通过MVC模型循环并返回
这是我的模型代码,它返回名称和IDHtml 通过MVC模型循环并返回,html,asp.net-mvc,model-view-controller,model,Html,Asp.net Mvc,Model View Controller,Model,这是我的模型代码,它返回名称和ID public class AccountType { public int Id { get; set; } public string Name { get; set; } public static AccountType[] ValidAccountTypes { get { return new[] { new Accoun
public class AccountType
{
public int Id { get; set; }
public string Name { get; set; }
public static AccountType[] ValidAccountTypes
{
get
{
return new[]
{
new AccountType
{
Id = 1,
Name = "Vendor"
},
new AccountType
{
Id = 2,
Name = "Customer"
},
new AccountType
{
Id = 3,
Name = "Demo"
}
};
}
}
}
我试图返回html并循环以下内容:
@model DemoApplication.Models.AccountType
@foreach (var x in Model.Name)
{
<p> @x </p>
}
我得到System.NullReferenceException的错误:“对象引用未设置为对象的实例。我不太确定在这里做什么,因为我对MVC完全是新手……我读了一些文档,但没有用
更新:我自己通过反复试验找到了答案
@foreach (var x in DemoApplication.Models.AccountType.ValidAccountTypes)
{
<p> @x.Name </p>
}
我希望您自己能得到解决方案,但您也可以尝试使用以下代码,这有其优势
@model DemoApplication.Models.AccountType
@foreach (var x in Model.ValidAccountTypes)
{
<p> @x.Name </p>
}
通过放置上述内容,您可以拥有强类型视图,这在多种方面都很有用
强类型视图的优点:
我们得到
1.智能感知和
2.编译时错误检查
希望以上内容有用,请告诉我您的想法或反馈
谢谢
Karthik请在相关控制器中发布Actionmethod,因为这是您将ViewModel传递给View.Model.Name的地方。Name是一个字符串,您希望在Model.VaidAccountTypes上循环并输出@x.Name。谢谢Paul,这很有意义,但是当我将循环更改为仍然出错时,我已经解决了,非常感谢,您不需要在视图中直接使用静态。我更喜欢将静态类的使用保持在最低限度,尤其是在webapps中!考虑通过创建包含一个帐户类型集合的VIEW模型类来遵守MVC原则。您的控制器实例化此模型,并使用return Viewmodel将其传递给视图;然后,在您的视图中,您可以在Model.ValidAccountTypes中使用foreachvar枚举AccountTypes