2013-08-06 21 views
1

我收到錯誤「未將對象引用設置爲對象的實例」。當試圖爲我的MVC項目中的模型字段賦值時。我的模型(不是強類型的)在我看來,這樣被引用:MVC中的模型未被賦值

...Inherits="System.Web.Mvc.ViewPage<Project.Models.MyModel>" %> 

智能感知拿起爲MyModel的領域,當我在視圖中訪問它。我的模特張貼如下:

namespace Project.Models 
{ 
    public class MyModel 
    { 
     public int AddressId { get; set; } 
     public int AddressTypeId { get; set; } 
     .... 
    } 
} 

正如你所看到的,我做了一個在每個領域的設置,一切都是公開的。但是當我調試它時,只要我碰到與模型有關的任何東西,編譯器就會抱怨:「對象引用未設置爲對象的實例。」

這裏缺少什麼?

+3

你是如何傳遞模型的看法?你能展示這部分代碼嗎? – Andrei

+0

如何實例化模型,並顯示出現錯誤的行 – krilovich

+0

您是否曾經實例化過模型? –

回答

2

確保你通過一個模型來從渲染它的控制器操作這樣的觀點:

public ActionResult SomeAction() 
{ 
    MyModel model = ... fetch your model from somewhere 
    return View(model); // <!-- Notice how the model must be passed to the view 
} 

明明就是隨時隨地可以取回檢索您的模型必須確保函數模型不是空值。或者,您可以在視圖中測試模型在訪問其屬性之前是否不爲null,如果它爲null,則呈現一些替代內容。

0

你必須初始化你的模型第一

爲如:

 

    public ActionResult YourAction() 
    { 
     MyModel model = new MyModel(); 
     return View(model); 
    } 

+1

你的答案與15分鐘前發佈的答案有什麼不同? – Stijn