Hey all I'm new to MVC/Razor and I am wanting to simply display a year on the view page.
The view page code:
<p>© @Html.Raw(ViewBag.theDate) - Switchboard</p>
And my controller code:
public String getYear()
{
ViewBag.theDate = DateTime.Now.Year.ToString();
return View(ViewBag.theDate);
}
When viewing the page in IE it just prints out:
© - Switchboard
How can I call that controller function from my View using Razor?
You can add support for Pages to any ASP.NET Core MVC app by simply adding a Pages folder and adding Razor Pages files to this folder. Razor Pages use the folder structure as a convention for routing requests.
The ViewBag object value will be set inside Controller and then the value of the ViewBag object will be accessed in the cshtml file (View) using Razor syntax in ASP.Net MVC Razor.
ASP.NET MVC 5 for Beginners Razor is a markup syntax that lets you embed server-based code into web pages using C# and VB.Net. It is not a programming language. It is a server side markup language. Razor has no ties to ASP.NET MVC because Razor is a general-purpose templating engine.
You need a controller method, to use the ViewBag and to return a View
public ActionResult Index()
{
ViewBag.theDate = DateTime.Now.Year.ToString();
return View();
}
In the Index.cshtml
, simply use
<p>© @ViewBag.theDate - Switchboard</p>
You can use ViewData as well, like
ViewData["Year"] = DateTime.Now.Year.ToString(); // in controller/actionresult
and in your view(Razor) just write:
@ViewData["Year"]
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