C# ASP.NET-MVC4使用从控制器到视图的变量
我有这样一个控制器:C# ASP.NET-MVC4使用从控制器到视图的变量,c#,asp.net,asp.net-mvc,C#,Asp.net,Asp.net Mvc,我有这样一个控制器: public class PreviewController : Controller { // GET: Preview public ActionResult Index() { string name = Request.Form["name"]; string rendering = Request.Form["rendering"]; var information = new Inform
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);
}
}
在视图中,我正在尝试将信息命名为:
@ViewBag.information.name
我还试过:
@information.name
但两者都有相同的错误:
无法对空引用执行运行时绑定
我做错了什么?您必须在视图中使用
@Model.name
。不是@ViewBag.information.name
。此外,在视图顶部,您必须定义如下内容:
@model Mynamespace.InformationClass
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);
}
}
最好使用MVC的模型绑定特性。因此,改变你的行动方式如下:
@model Mynamespace.InformationClass
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);
}
}
您需要在操作中设置
ViewBag.InformationName
:
ViewBag.InformationName = name;
然后在您看来,您可以引用它:
@ViewBag.InformationName
或者,如果您试图在视图中使用模型数据,您可以通过以下方式引用它:
@Model.name
在视图中,只需键入
@Model.name
由于InformationClass是您的模型,您只需使用@model从视图中调用其属性,请将该示例添加到您的视图文件中
@model Your.Namespace.InformationClass
该行负责定义模型类型。之后,您只需使用:
@Model.name;