asp.net-mvc - asp.net mvc中的转发器foreach
问题描述
我正在使用 MVC 在 ASP.Net 中构建一个网站,需要列出一组结果,但代码中出现错误
模型:
public class Customers
{
public int Id { get; set; }
public string Name { get; set; }
public List<Customers> Itemlst { get; set; }
}
控制器:
public ActionResult List()
{
Customers itemobj = new Customers();
return View(itemobj);
}
看法:
@foreach(var item in Model.Itemlst)
{
<tr>
<td>Items ID:</td>
<td>@item.ID</td>
<td>Items Name:</td>
<td>@item.Name</td>
</tr>
}
</table>
解决方案
从NullReferenceException
您收到的消息中,我们可以看到问题是由于Itemlst
未初始化。解决此问题的方法之一就是确保在创建对象时存在有效列表:
public class Customers
{
public Customers()
{
Itemlst = new List<Customers>();
}
public int Id { get; set; }
public string Name { get; set; }
public List<Customers> Itemlst { get; set; }
}
因此,如果需要,您可以在操作中将值添加到列表中:
public ActionResult List()
{
Customers itemobj = new Customers();
var example = new Customers ();
example.Id = 1;
example.Name = "Example";
itemobj.Add();
return View(itemobj);
}
我不知道您是否只是将此作为您问题的示例,但我不禁注意到有些奇怪。您可以使用不同的东西,例如:
public class ViewModel // Name to what makes sense to you
{
// Some other properties...
public List<Customer> Customers { get; set; }
}
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
}
或者您可以List<Customer>
直接在视图中用作模型(是的,您的模型可以是一个简单的对象列表的对象)。
推荐阅读
- android - 如何使用导航组件处理片段中的片段?
- python - 嵌套函数通过python中的外部函数返回一个变量
- javascript - .css 和 .js 扩展名的 .htaccess RewriteRule 被阻止/忽略?
- linux - 如何在管道之间的 bash 脚本中删除权限?
- c# - RedirectToRoute 在 ASP.NET MVC 项目中不起作用
- asp.net-core - Razor 页面 - 重定向到路由
- sql - 拆分 SQL Server 列值
- ios - IOS 企业发行版在某些 ipad 上安装失败 - 已添加、修改或删除已签名的资源
- python - 使用 Windows 身份验证通过 Python 登录发送邮件
- ios - 合并:发布者有时会失去价值并完成