【问题标题】:Post MVC form calling a controller action view that requires a viewmodel. Why does the ViewModel not get sent to the view?发布 MVC 表单调用需要视图模型的控制器操作视图。为什么 ViewModel 没有被发送到视图?
【发布时间】:2015-04-20 00:33:25
【问题描述】:

我有一个发布到控制器操作的 MVC BeginForm 元素:

[HttpPost]
public ActionResult Create(FormViewModel Model)
{
     ... Some form saving logic
     return View()
}

但是当索引视图被渲染时,我得到一个“对象引用未设置为对象的实例”错误。

我的索引视图是这样的:

public ActionResult Index()
{
    ...Create The IndexViewModel 
    return View(ViewModel)
}

如何在发布后调用控制器操作以生成视图模型?

如果我从 HTTP 创建中调用索引控制器操作,例如:

[HttpPost]
public ActionResult Create(FormViewModel Model)
{
     ... Some form saving logic
     return Index()
}

我会得到一个'传递到字典的模型项是'IndexViewModel'类型的,但是这个字典需要一个CreateViewModel类型的模型项。

视图引用与将参数传递给视图的控制器操作关联的模型。

【问题讨论】:

  • IndexViewModelFormViewModel 是两个不同的东西。显示 IndexCreate 的视图
  • 您想查看视图的代码吗?他们基本上只是调用模型,就像在 Create 的情况下,'@model Project.ViewModels.CreateViewModel' 和在 Index 的情况下,'@model Project.ViewModels.IndexViewModel'。从 url 调用时视图正确呈现,但是当我发布创建表单时,当它尝试导航回索引时出现错误。
  • 您没有导航回Index()!在第一个 sn-p 中,您没有返回模型(您显然试图在视图中访问模型的属性,但您不会很难准确地说出您做错了什么)。在第 3 个 sn-p 中,如果要重定向,则需要 return RedirectToAction("Index");
  • 你摇滚。如果您想使用该代码添加答案 sn-p 我会接受它。无论如何,我会支持你的评论。

标签: c# asp.net-mvc asp.net-mvc-4


【解决方案1】:

在第一个 sn-p 中,您没有返回模型(模型将为 null,因此访问模型的属性(例如 <div>@Model.SomeProperty</div> 将引发异常)

[HttpPost]
public ActionResult Create(FormViewModel model)
{
    ... Some form saving logic
    return View(model); // change this so you return the model to the view
}

在第3个sn-p中,要重定向到index方法,需要是

[HttpPost]
public ActionResult Create(FormViewModel Model)
{
    ... Some form saving logic
    return RedirectToAction("Index"); // Change this to redirect to the Index() method
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-07
    • 2017-07-12
    • 1970-01-01
    • 1970-01-01
    • 2018-04-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多