【问题标题】:How should I send viewmodel to Create method in Controller?我应该如何将 viewmodel 发送到 Controller 中的 Create 方法?
【发布时间】: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


    【解决方案1】:

    我猜原因是你没有你的帖子对象的实例。试着让你的 viewModel 变成这样:

    public class PostsViewModel
    {
        public string PostText {get;set;} // don`t forget to make it like property, not just a field
    }
    

    然后在你的控制器中创建一个实例:

    public ActionResult Create(PostsViewModel p) 
    {
       Post post = new Post{ postText = p.PostText};
       //and do what you want with it
    }
    

    【讨论】:

    • 我可以在 Create 方法参数 PostsViewModel p 中获取 p.post 的值。但我仍然将 p.posts 设为 null 。
    • 你根本不用它,是吗?你到底在玩什么?)如果我没听错的话,你的帖子数组必须在 dbcontext 之类的地方
    • 我不能在参数中获得正确的 p.posts 值吗?是的,这些值可以从 dbContext 获得。我只想知道为什么参数中的值是null。
    • 你不要t create any object. You got value from that post, but your inctance is still anonymous, so you getting null.:D You can try to make your post property in viewmodel as virtual. Thats 会帮助你不被空置
    • 使用带有 posts 属性的 virtual 仍然给出相同的结果。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-12
    • 2022-01-20
    • 1970-01-01
    • 2019-11-06
    • 1970-01-01
    相关资源
    最近更新 更多