Reputation: 10542
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?
Upvotes: 6
Views: 17635
Reputation: 1225
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"]
Upvotes: 2
Reputation: 5943
You need a controller ActionResult
that returns a View, like so:
public ActionResult MyView()
{
//ViewBag.ShowTheYear = DateTime.Now.Year.ToString();
//You do not call a method from the view.. you do it in the controller..
// Using your example
ViewBag.ShowTheYear = getYear();
return View();
}
getYear
method:
public String getYear()
{
return DateTime.Now.Year.ToString();
}
Then in your MyView.cshtml
<p>© @Html.Raw(ViewBag.ShowTheYear) - Switchboard</p>
Let me know if this helps!
Upvotes: 1
Reputation: 196
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>
Upvotes: 9