Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC best practice for displaying static generated data

Question background:

I have a two page MVC 4 web app. The first page's view currently has its data manually typed into the View as its static i.e nothing is being passed to the View from its associated Controller method, as shown:

Index controller method:

Public ActionResult Index()
{
  return View();
}

Index.cshtml View:

<div class="titleHeader">Welcome To This Test Example</div>

Best practice:

Is the above example OK to use, or should I generate a ViewModel object on the Index controller, populate the static data then return it to the View? As Shown:

Index Controller Index method with ViewModel:

Public ActionResult Index()
{
  HomePageVM homepageVM = new HomePageVM
  {
    WelcomeMessage = "Welcome To This Test Example";
  };

  return View(homepageVM);
}

Index.cshtml now bound to the HomePageVM ViewModel:

@model TestPage.Models.HomePageVM

<div class="titleHeader">@Model.WelcomeMessage</div>
like image 313
Dev Avatar asked Jan 09 '23 04:01

Dev


1 Answers

I think (opinion), it's best to use Resource files for static data.

With these Resource file you will be able to easily port to a multi language website.

Basically you'll need to create resx files, make the entries public.

In your cshtml you can access it by:

<div class="titleHeader">@Resources.WelcomeMessage</div>

Depending on the UIThread's culture info it is able to select the appropriate language.

You can find a tutorial here: http://www.codeproject.com/Articles/778040/Beginners-Tutorial-on-Globalization-and-Localizati

As for your options:

1) There is really no need to create a ViewModel for static data unless you'll expect it to be dynamic in the future (although it's bad habit to develop now for future requirements).

2) Hard coded strings in the cshtml, it possible, but not suited for multi-language. There is 1 benefit I would like to mention: it's easier for non-developers to alter the html.

like image 173
Stefan Avatar answered Jan 18 '23 12:01

Stefan