[英]My model is always null, why? ASP.Net MVC
This is my model : 这是我的模特:
public class Stages
{
public int Id { get; set; }
public string Code { get; set; }
public string Name { get; set; }
public string Des { get; set; }
public string View_Count { get; set; }
}
My Controller : 我的控制器:
public ActionResult ViewStages()
{
return View();
}
And my view : 我的观点是:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<IEnumerable<Project.Models.Stages>>" %>
//Some Code...
<% foreach (var item in Model)
{ %>
<tr>
<td>
<%: Html.DisplayFor(modelItem => item.Code)%>
</td>
<td>
<%: Html.DisplayFor(modelItem => item.Name)%>
</td>
<td>
<%: Html.DisplayFor(modelItem => item.Des)%>
</td>
<td>
<%: Html.DisplayFor(modelItem => item.View_Count)%>
</td>
<td>
<%: Html.ActionLink("Edit", "Edit", new { id = item.Id })%> |
<%: Html.ActionLink("Details", "Details", new { id = item.Id })%> |
<%: Html.ActionLink("Delete", "Delete", new { id = item.Id })%>
</td>
</tr>
<% }%>
</table>
</asp:Content>
And I always get this error : Object reference not set to an instance of an object. 我总是得到这个错误:对象引用没有设置为对象的实例。 and the error occurred when it reaches the foreach loop. 并且当它到达foreach循环时发生错误。 What is the problem? 问题是什么?
Because you didn't initialize it 因为你没有初始化它
public ActionResult ViewStages()
{
//this initialize your model
var viewModel=new List<Stages>()
{
new Stages()
{
Id = 1,
Code = "any code",
//etc
}
};
return View(viewModel); //you have to pass the model to the view
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.