gpt4 book ai didi

c# - ASP.NET - MVC 4 使用从 Controller 到 View 的变量

转载 作者:太空狗 更新时间:2023-10-29 22:15:52 24 4
gpt4 key购买 nike

我有这样的 Controller :

public class PreviewController : Controller
{
// GET: Preview
public ActionResult Index()
{
string name = Request.Form["name"];
string rendering = Request.Form["rendering"];

var information = new InformationClass();
information.name = name;
information.rendering = rendering;

return View(information);
}
}

在 View 中,我正在尝试像这样使用 information.name:

@ViewBag.information.name

我也试过:

@information.name

但是两者都得到了同样的错误:

Cannot perform runtime binding on a null reference

我做错了什么?

最佳答案

您必须在 View 中使用@Model.name。不是 @ViewBag.information.name。同样在您的 View 之上,您必须定义如下内容:

@model Mynamespace.InformationClass

而且使用MVC的模型绑定(bind)功能会更好。因此,像这样更改您的操作方法:

public class PreviewController : Controller
{
[HttpPost] // it seems you are using post method
public ActionResult Index(string name, string rendering)
{
var information = new InformationClass();
information.name = name;
information.rendering = rendering;

return View(information);
}
}

关于c# - ASP.NET - MVC 4 使用从 Controller 到 View 的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32570297/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com