Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.net MVC 5 ViewBag using Razor

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>&copy; @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?

like image 271
StealthRT Avatar asked Dec 19 '16 18:12

StealthRT


People also ask

Can you use MVC with Razor pages?

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.

How do I find the ViewBag value of a Razor?

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.

What is Razor syntax MVC 5?

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.


2 Answers

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>&copy; @ViewBag.theDate - Switchboard</p>
like image 52
FBO Avatar answered Sep 25 '22 22:09

FBO


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"]
like image 34
Shaahin Avatar answered Sep 22 '22 22:09

Shaahin