0

I'm just learning MVC4, so this is a very basic question.

I have a string of text that I'd like to display on multiple pages. What is the best practice to accomplish this (other than copying/pasting it into each cshtml)?

tereško
  • 58,060
  • 25
  • 98
  • 150
Rethic
  • 1,054
  • 4
  • 21
  • 36
  • 2
    If it's not view specific, and it's universal you could add it to the _layout – Maess Nov 08 '12 at 16:21
  • 2
    You could also consider storing your strings as resources and retrieving where necessary through the a `ResourceManager`, this has the added benefit of being able to do localization down the road if you ever need to. – Quintin Robinson Nov 08 '12 at 16:29

2 Answers2

1

If it's going to be on every page, put it in the _layout file as Maess suggested. If you only want it in specific views, you can create a partial view and just insert that wherever you want it to display.

Shawn Steward
  • 6,773
  • 3
  • 24
  • 45
  • Thank you. I ended up going through the partial view route. It seems to work fine for my purposes. – Rethic Nov 08 '12 at 19:29
1

You could define them in code within a static class:

namespace MyNamespace
{
    public static class MyConstants
    {
        public static string message = "Whatever I wanted to say";
    }
}

and use them in cshtml:

@using MyNamespace
<h1>@ViewBag.Title @constants.message    </h1>

Also have a look at the answers to VikViks question: Share constants between C# and Javascript in MVC Razor

Community
  • 1
  • 1
Frank im Wald
  • 896
  • 1
  • 11
  • 28
  • Cool... I'll have to try this out when I get a chance to breathe. I had read a number of articles saying "ViewBag is evil", so was worried about being lambasted if I used it. – Rethic Nov 08 '12 at 19:32