2011-07-09 27 views
0

Picture類型的一個對象,它包含一個列表的評論在這裏看到源代碼http://pastebin.me/21148a93065bddb7302e160f5a0ac1fb充分利用SQL Server中的單個對象的視圖

我當時想採取Picture.ID,並顯示具有獨特的圖像從我的數據庫ID

所以我做了我的GalleryController http://pastebin.me/21148a93065bddb7302e160f5a0acb02一個ActionResult的評論一個HTTPGET

我再有這樣的觀點,即應顯示請求的圖像,並在其列表中的評論http://pastebin.me/21148a93065bddb7302e160f5a0acb02

但我不知道如果沒有初始化它的列表,或者如果我只是做是錯誤的,但我得到一個錯誤

Server Error in '/' Application.
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details:
System.NullReferenceException: Object reference not set to an instance of an object.

源錯誤:http://pastebin.me/21148a93065bddb7302e160f5a0ad965

+2

你應該嘗試在您的文章直接發佈源的** **有關位 - 交聯到一個單獨的網站是一個有點亂,需要大量的點擊來自您的閱讀..... –

+0

是的,但是標記該代碼的代碼往往看起來還是非常錯誤的,特別是如果它的部分/完全的HTML代碼 – Mech0z

+0

如果您發佈的代碼,XML或數據樣本,** **請在高亮文本編輯器的線,然後單擊「代碼示例」按鈕('{}')在編輯器工具欄上進行恰當的格式化和語法突出顯示! –

回答

0

,因爲我不能讓它只解析單個對象(我知道總會有最大一個結果,因爲它在數據庫中搜索與主鍵)

所以我的代碼,現在是

 [HttpGet] 
    public ActionResult Comment(string ID) 
    { 
     int id = Convert.ToInt32(ID); 
     if (ID != null) 
     { 
      try 
      { 
       var model = from r in _db.Gallery 
          where r.ID == id 
          select r; 

       return View(model); 
      } 
      catch 
      { 
      } 
     } 

     return View(); 
    } 

而且

@model IEnumerable<firstweb4.Models.Picture> 

@{ 
    ViewBag.Title = "Comment"; 
} 

@if (Model != null) 
{ 
    foreach (var item in Model) 
    { 
    <a href="@item.Path"><img src="@item.Path" alt="@item.Title" width="250px" /> </a> 
    <table> 
     <tr> 
      <th> 
       Posted by 
      </th> 
      <th> 
       Comment 
      </th> 
      <th> 
       Posted on 
      </th> 
     </tr>  
    @foreach (var comment in item.PictureComments) 
    { 
     <tr> 
      <td> 
       @comment.Auther 
      </td> 
      <td> 
       @comment.Text 
      </td> 
      <td> 
       @comment.PostedTime 
      </td> 
     </tr> 
    } 
    </table> 
    } 
} 

所以我通過了singleitem收集我解析itterate和現在的作品。

2

讓我們來看看操作方法有問題。首先,我看到這一點,這幾乎從來不應該存在:

  catch 
      { 
      } 

所以,如果一個異常被拋出,你只是吞嚥了起來,永遠不會知道它。這會導致返回沒有傳入模型的視圖,因此強類型視圖中引用的模型爲空。這似乎是發生事情的一個很好的可能性。

另外,爲什麼你會在你的foreach循環裏面覆蓋ViewBag.Picture?那真的是你想要做的嗎?

希望這將讓你在正確的道路上,你會迅速得到潛在的問題。