MVC - Variables

by
Jeremy Canfield |
Updated: March 20 2020
| MVC articles
Let's start with a very simple variable. The following can be entered in a razor view file.
@{
string sample = "Hello World";
}
@Html.Raw(sample)
This would produce the following.
Text can be passed from the Controller to a View using ViewBag.Message.
CONTROLLER
public ActionResult Index()
{
ViewBag.Message = "Hello World";
return View();
}
VIEW
@ViewBag.Message
This would produce the following.
To pass more than one variable to the view, do the following.
CONTROLLER
public ActionResult Index()
{
var abc = "Hello";
ViewBag.abc = abc;
var xyz = "World";
ViewBag.xyz = xyz;
return View();
}
VIEW
@Model.site
@Model.username
@ViewBag.abc
@ViewBag.xyz
This would produce the following.
Did you find this article helpful?
If so, consider buying me a coffee over at