2012-12-13 85 views
-1

我有我不能修復這個基本的錯誤...對象引用不設置到對象基本誤差System.NullReferenceException

我使用asp.net mvc4與EF的實例

我控制器

public class PostController : Controller 
    { 
     private UsersContext db = new UsersContext(); 

     public ActionResult Index() 
     { 
      return View(db.Posts.ToList()); 
     } 

     public ActionResult Create() 
     { 
      return View(); 
     } 

     [HttpPost] 
     public ActionResult Create(FormCollection values) 
     { 
      var post = new Post(); 
      TryUpdateModel(post); 

      if(ModelState.IsValid) 
      { 
       var context = new UsersContext(); 
       var username = User.Identity.Name; 
       var user = context.UserProfiles.SingleOrDefault(u => u.UserName == username); 
       var userid = user.UserId; 
       // var firstname = user.FirstName; 

       post.UserId = userid; 
       post.Date = DateTime.Now; 

       db.Posts.Add(post); 
       db.SaveChanges(); 
      } 
      return View("Index"); 
     } 

和我的觀點:

@model IEnumerable<MyProject.Models.Post> 

@{ 
    ViewBag.Title = "Index"; 
} 

<h2>Index</h2> 

<p> 
    @Html.ActionLink("Create New", "Create") 
</p> 
<table> 
    <tr> 
     <th> 
      @Html.DisplayNameFor(model => model.Content) 
     </th> 
     <th> 
      @Html.DisplayNameFor(model => model.Date) 
     </th> 
     <th></th> 
    </tr> 

    @foreach (var item in Model) { //**line with error** 

    <tr> 
     <td> 
       @Html.DisplayFor(modelItem => item.Content) 
     </td> 
     <td> 
       @Html.DisplayFor(modelItem => item.Date) 
     </td> 
     <td> 
      @Html.ActionLink("Edit", "Edit", new { id=item.PostId }) | 
      @Html.ActionLink("Details", "Details", new { id=item.PostId }) | 
      @Html.ActionLink("Delete", "Delete", new { id=item.PostId }) 
     </td> 
    </tr> 
} 
</table> 

感謝您的幫助

+3

你在哪一點得到錯誤? –

回答

8

您忘記了在控制器中的GET操作之後將模型發送到視圖。你return說法或許應該是:

public ActionResult Create() 
    { 
     return View("Create", new Post()); 
    } 

你必須爲模型提供的東西,或者它會在視圖null

你可能會與你的POST方法爲好,它返回了同樣的問題:

return View("Index"); 

不是這樣做,你應該只是重定向到Index操作:

return RedirectToAction("Index"); 

另外,您只需要在成功時執行此操作 - 如果模型狀態無效,您可能需要返回創建屏幕以顯示錯誤。所以,你的崗位的行動最終會是這樣的:

[HttpPost] 
    public ActionResult Create(FormCollection values) 
    { 
     var post = new Post(); 
     TryUpdateModel(post); 

     if(ModelState.IsValid) 
     { 
      var context = new UsersContext(); 
      var username = User.Identity.Name; 
      var user = context.UserProfiles.SingleOrDefault(u => u.UserName == username); 
      var userid = user.UserId; 
      // var firstname = user.FirstName; 

      post.UserId = userid; 
      post.Date = DateTime.Now; 

      db.Posts.Add(post); 
      db.SaveChanges(); 

      return RedirectToAction("Index"); 
     } 

     return View("Create", post); 
    } 
+0

謝謝,現在我不會再犯同樣的錯誤了 – Alternative

0

Object reference not set to an instance of an object意味着你試圖訪問一個對象,它是null的屬性或方法。