【发布时间】:2019-02-09 18:24:02
【问题描述】:
我正在尝试将数据从视图发送到控制器的 Create 方法。但是在调用 create 方法时,视图模型参数正在获取 null 值。
在我看来,我想添加一个项目并显示已添加项目的列表。 我尝试向 create 方法发送数据,但它的视图模型参数正在获取空值。
在下面的代码中,每当点击 Create 方法时 p.posts 的值和 p.post 为空。如何在这里获取 p.post 和 p.posts 的值?
控制器方法
public ActionResult Create(PostsViewModel p) {}
查看模型
public class PostsViewModel
{
public IEnumerable<Post> posts;
public Post post;
}
查看
@model NotesWebApplication.ViewModels.PostsViewModel
...
@using (Html.BeginForm()) {
...
@Html.EditorFor(model => model.post.postText, new { htmlAttributes = new { @class = "form-control" } })
...
<input type="submit" value="Create" class="btn btn-default" />
如果我想添加 Bind 那么在我的 Create 方法中也应该添加
[Bind(Include="postText")]
或
[Bind(Include="post.postText")]
更新
我在 PostsViewModel 类中做了以下更改
public class PostsViewModel
{
public IEnumerable<Post> posts { get; set; }
public Post post { get; set; }
}
控制器中的Create方法改为
[HttpPost]
public ActionResult Create([Bind(Include="post, posts")]PostsViewModel p) {}
这就是 httpget Create 方法的样子
// GET: Posts/Create
public ActionResult Create()
{
PostsViewModel postsViewModel = new PostsViewModel();
postsViewModel.posts = db.Posts;
postsViewModel.post = new Post();
return View(postsViewModel);
}
现在,当我提交表单时,控制器参数中的 p.post 会收到所需的值。但是 p.posts 仍然为空。为什么会这样?
【问题讨论】:
标签: asp.net model-view-controller viewmodel