我有两个模型,如下所示,并尝试从一个视图将其中一个插入数据库.我创建了一个视图模型来试图这样做.
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); }
这不断抛出错误
Object reference not set to an instance of an object.
在线上blog.Blog.User =用户.
对我做错了什么的想法?
编辑
我检查了POST数据,它是所有和正确的,但它发布的一切都是Blog.Title =和BlogPost.Body =所以控制器中的viewmodel没有收到任何东西.如果我将控制器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>