Asp.net-Mvc-3

MVC3 - 使用 ViewModel 插入 - 對象引用未設置為對象的實例

  • November 12, 2017

我有兩個模型,如下所示,並試圖從一個視圖將每個模型插入數據庫。我創建了一個視圖模型試圖做到這一點。

public class Blog
{
   public int BlogID { get; set; }
   public string Title { get; set; }
   public DateTime CreatedOn { get; set; }

   public virtual User User { get; set; }
   public virtual ICollection<BlogPost> Posts { get; set; }     
}

public class BlogPost
{
   public int PostID { get; set; }
   public string Body { get; set; }
   public DateTime CreatedOn { get; set; }

   public int UserID { get; set; }
   public virtual User User { get; set; }
}

public class BlogViewModel
{
   public Blog Blog { get; set; }
   public BlogPost BlogPost { get; set; }
}

使用我發佈到創建控制器的視圖模型:

[HttpPost]
   public ActionResult Create(BlogViewModel blog)
   {
       if (ModelState.IsValid)
       {
           User user = unit.UserRepository.GetUser();
           blog.Blog.User = user;
           blog.Blog.CreatedOn = DateTime.Now;

           unit.BlogRepository.Insert(blog.Blog);
           unit.BlogPostRepository.Insert(blog.BlogPost);
           unit.Save();

           return RedirectToAction("Index");  
       }

       return View(blog);
   }

這不斷拋出錯誤

你呼叫的對像是空的。

就行了blog.Blog.User = user

對我做錯了什麼有任何想法嗎?

編輯 我檢查了 POST 數據,它都在那裡並且正確,但它正在發布所有內容Blog.Title =BlogPost.Body =因此控制器中的視圖模型沒有收到任何內容。如果我將控制器 actionresult 更改為:

public ActionResult Create(Blog blog, BlogPost post)

然後一切正常。那麼為什麼不以 viewmodel 格式發送數據呢?我在您的視圖和控制器之間使用基於顯式視圖模型的互動

@model Test.Models.BlogViewModel
@using (Html.BeginForm())
{
   @Html.ValidationSummary(true)
   <fieldset>
       <legend>Blog</legend>
       <div class="editor-label">
           @Html.LabelFor(model => model.Blog.Title)
       </div>
       <div class="editor-field">
           @Html.EditorFor(model => model.Blog.Title)
           @Html.ValidationMessageFor(model => model.Blog.Title)
       </div>
       <div class="editor-label">
           @Html.LabelFor(model => model.BlogPost.Body)
       </div>
       <div class="editor-field">
           @Html.EditorFor(model => model.BlogPost.Body)
           @Html.ValidationMessageFor(model => model.BlogPost.Body)
       </div>
       <p>
           <input type="submit" value="Create" />
       </p>
   </fieldset>
}
<div>
   @Html.ActionLink("Back to List", "Index")
</div>

只需重命名您的操作參數:

public ActionResult Create(BlogViewModel viewModel)

存在衝突,因為您的 action 參數被呼叫blog,而您的視圖模型 ( BlogViewModel) 有一個名為 的屬性Blog。問題是預設模型綁定器不再知道在這種情況下該做什麼。

哦,如果您絕對需要呼叫您的操作參數,blog那麼您還可以重命名Blog視圖模型上的屬性。

我以前也遇到過這種情況。當您從視圖發送的數據不是格式時,就會發生這種情況,MVC 預設模型綁定引擎可以理解或映射到您的視圖模型對象。嘗試使用“FireBug”並查看數據是如何通過 POST 傳遞的。然後看看,是否可以將這些數據映射到您的視圖模型的定義。

還有一件事,您是使用 jQuery 傳遞數據還是使用基於視圖模型的顯式視圖和控制器之間的互動?

引用自:https://stackoverflow.com/questions/8020474