简体   繁体   English

ASP.NET - MVC 4使用从控制器到视图的变量

[英]ASP.NET - MVC 4 using a variable from a controller to a view

I have this controller like so: 我有这样的控制器:

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);
    }
}

and in the view, I am trying to the information.name like so: 在视图中,我正在尝试信息.name如下:

@ViewBag.information.name

I also tried just: 我也尝试过:

@information.name

but got the same error for both: 但两者都有相同的错误:

Cannot perform runtime binding on a null reference 无法对空引用执行运行时绑定

What am I doing wrong? 我究竟做错了什么?

You must use @Model.name in view. 您必须在视图中使用@Model.name Not @ViewBag.information.name . 不是@ViewBag.information.name Also in top of your view you must define something like this: 同样在视图的顶部,您必须定义如下内容:

@model Mynamespace.InformationClass

And it would be better to use MVC's model binding feature. 使用MVC的模型绑定功能会更好。 Therefore change your action method like this: 因此,请更改您的操作方法:

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);
    }
}

In the view just type 在视图中输入

@Model.name

Since InformationClass is your model you just call its properties from the view using @Model 由于InformationClass是您的模型,您只需使用@Model从视图中调用其属性

You need to set ViewBag.InformationName in your action: 您需要在操作中设置ViewBag.InformationName

ViewBag.InformationName = name;

And then in your view you could reference it: 然后在您的视图中,您可以参考它:

@ViewBag.InformationName

Or if you're trying to work with the model data in the view, you'd reference it through this: 或者,如果您尝试使用视图中的模型数据,则可以通过以下方式引用它:

@Model.name

Please add that sample to your view file 请将该示例添加到您的视图文件中

   @model Your.Namespace.InformationClass

That line is responsible for defining your model type. 该行负责定义您的模型类型。 And after that you can just use: 之后你可以使用:

   @Model.name;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM