C# 后MVC表单调用需要viewmodel的控制器操作视图。为什么不将ViewModel发送到视图?

C# 后MVC表单调用需要viewmodel的控制器操作视图。为什么不将ViewModel发送到视图?,c#,asp.net-mvc,asp.net-mvc-4,C#,Asp.net Mvc,Asp.net Mvc 4,我有一个MVCBeginForm元素,它发布到控制器操作: [HttpPost] public ActionResult Create(FormViewModel Model) { ... Some form saving logic return View() } 但是当索引视图被渲染时,我得到一个“对象引用未设置为对象实例”错误 我的索引视图如下所示: public ActionResult Index() { ...Create The IndexViewMo

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

[HttpPost]
public ActionResult Create(FormViewModel Model)
{
     ... Some form saving logic
     return View()
}
但是当索引视图被渲染时,我得到一个“对象引用未设置为对象实例”错误

我的索引视图如下所示:

public ActionResult Index()
{
    ...Create The IndexViewModel 
    return View(ViewModel)
}
如何在发布后调用控制器操作以生成视图模型

如果我从HTTP调用Index Controller操作,请如下所示:

[HttpPost]
public ActionResult Create(FormViewModel Model)
{
     ... Some form saving logic
     return Index()
}
我将得到一个“传入字典的模型项的类型为'IndexViewModel',但此字典需要类型为
CreateViewModel
的模型项。”


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

在第一个代码段中,您没有返回模型(模型将为null,因此访问模型的属性(例如
@model.SomeProperty
将引发异常)

在第三个代码段中,如果要重定向到index方法,则需要

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

IndexViewModel
FormViewModel
是两个不同的东西。显示
Index
Create
的视图您想查看视图的代码吗?它们基本上只需调用模型,就像在Create中调用“@model Project.ViewModels.CreateViewModel”和在Index中调用“@model Project.ViewModels.Inde”一样xViewModel'。当从URL调用视图时,视图呈现正确,但是当我发布创建表单时,当它尝试导航回索引时,我会出现错误。您没有导航回
索引()
!在第一个代码段中,您没有返回模型(显然,您试图在视图中访问模型的属性,但您不会很难准确地说出您的错误所在)。在第三个代码段中,如果您想重定向,则需要
return RedirectToAction(“Index”)
你太棒了。如果你想用那段代码添加答案,我会接受的。无论如何,我会投票支持你的评论。
[HttpPost]
public ActionResult Create(FormViewModel Model)
{
    ... Some form saving logic
    return RedirectToAction("Index"); // Change this to redirect to the Index() method
}