2013-02-15 91 views
0

這是我的模型:我的模型始終爲空,爲什麼? ASP.Net MVC

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; } 
    } 

我的控制器:

public ActionResult ViewStages() 
    { 
     return 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> 

,我總是得到這樣的錯誤:對象引用未設置到一個對象的一個​​實例。 ,並且在到達foreach循環時發生錯誤。問題是什麼?

回答

2

因爲你沒有初始化

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 
    } 
+0

好極了!非常感謝Massimiliano – Angelina 2013-02-15 11:37:15

相關問題