MVC3 - 使用ViewModel插入 - 未将对象引用设置为对象的实例

Mic*_*ott 14 entity-framework viewmodel asp.net-mvc-3

我有两个模型,如下所示,我试图从一个视图中插入一个模型到数据库.我创建了一个视图模型,试图这样做.

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; }
}
Run Code Online (Sandbox Code Playgroud)

使用视图模型我发布到创建控制器:

[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);
    }
Run Code Online (Sandbox Code Playgroud)

这继续抛出错误

你调用的对象是空的.

就行了blog.Blog.User = 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>
Run Code Online (Sandbox Code Playgroud)

Dar*_*rov 35

只需重命名您的操作参数:

public ActionResult Create(BlogViewModel viewModel)
Run Code Online (Sandbox Code Playgroud)

存在冲突,因为您的action参数被调用blog,但您的view model(BlogViewModel)具有一个名为的属性Blog.问题是默认模型绑定器不再知道在这种情况下该做什么.

哦,如果您绝对需要调用您的action参数,blog那么您还可以Blog在视图模型上重命名该属性.