ASP.net MVC 5 ViewBag using Razor

10,594

Solution 1

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>

Solution 2

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"]

Solution 3

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>&copy; @Html.Raw(ViewBag.ShowTheYear) - Switchboard</p>

Let me know if this helps!

Share:
10,594
StealthRT
Author by

StealthRT

Updated on June 09, 2022

Comments

  • StealthRT
    StealthRT almost 2 years

    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?

  • StealthRT
    StealthRT over 7 years
    How do I call something from a method other than Index()?
  • FBO
    FBO over 7 years
    the MVC pattern requires you tu use a controller method to return a view. In that method you can call other method from other services. Ex ViewBag.theDate = DateHelper.getYear()
  • StealthRT
    StealthRT over 7 years
    That does help. Thanks BviLLe_Kid