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

I have a controller like this:

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 try to .name information like so:

@ViewBag.information.name

I also tried just:

@information.name

but got the same error for both:

Unable to bind while executing null reference

What am I doing wrong?

+4
source share
4 answers

In the view, just type

@Model.name

Since InformationClass is your model, you simply call its properties from the view using @Model

+4
source

You must use @Model.namein sight. Do not @ViewBag.information.name. Also at the top of your view, you should define something like this:

@model Mynamespace.InformationClass

MVC. :

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

You need to set ViewBag.InformationNamein action:

ViewBag.InformationName = name;

And then, in your opinion, you can refer to it:

@ViewBag.InformationName

Or, if you are trying to work with model data in a view, you should reference this via:

@Model.name
+2
source

Add this sample to your view file.

   @model Your.Namespace.InformationClass

This line is responsible for determining the type of your model. And after that you can simply use:

   @Model.name;
+1
source

Source: https://habr.com/ru/post/1607310/


All Articles