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:
@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?
The other way of passing the data from Controller to View can be by passing an object of the model class to the View. Erase the code of ViewData and pass the object of model class in return view. Import the binding object of model class at the top of Index View and access the properties by @Model.
ViewBag. ViewBag is a very well known way to pass the data from Controller to View & even View to View. ViewBag uses the dynamic feature that was added in C# 4.0. We can say ViewBag=ViewData + Dynamic wrapper around the ViewData dictionary.
OK, the simple answer is, you need to know the . Net type being returned from your query when you set the scrap variable in your controller. Whatever that type is, that's what type your @model needs to be. Either that, or use the ViewBag --but again, without IntelliSense support since it's a dynamic .
ViewData, ViewBag, and TempData are used to pass data between controller, action, and views. To pass data from the controller to view, either ViewData or ViewBag can be used. To pass data from one controller to another controller, TempData can be used.
You must use @Model.name
in view. Not @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. 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
You need to set ViewBag.InformationName
in your action:
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With