MVC Best Practice for Displaying Static Data

Question:

I have an MVC web application with two pages. In the first view of the page, its data is currently being manually entered into the view as its static ie nothing is passed to the view from its associated controller method as shown below:

Pointing 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 do I need to create a ViewModel object on the index controller, populate with static data and return it to the view? As shown:

Pointer index method with ViewModel:

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

  return View(homepageVM);
}

      

Index.cshtml is now tied to the HomePageVM ViewModel:

@model TestPage.Models.HomePageVM

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

      

+3


source to share


3 answers


Based on the principle of not gold plating your code.

You don't need a view model (right now), so don't add one. If you need a view model later, then just add it. Your goal should be to create the simplest possible solution . To me this means that the view model (or any other solution other than pure HTML) just adds unnecessary complexity.




The answer from stefan about resources again seems gold plated to me. It is based on:

will be able to easily transfer to a website with multiple languages.

Is your site multilingual? Will it ever be? If not , it's gilding.

+3


source


I think (opinion) it is better to use files Resource

for static data.

With this resource file, you can easily transfer to a multi-language website.

Basically you need to create files resx

, make records publicly available.

In your cshtml, you can access it:

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

      



Depending on the UIThread culture information, it can choose 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 no need to create a ViewModel for static data unless you expect it to be dynamic in the future (although this is a bad habit to design for future requirements now).

2) Hardcoded strings in cshtml maybe, but not suitable for multilingualism. There is 1 advantage I would like to mention: it is easier for non-developers to change the html.

+3


source


I'm not just a code guru, but: Why use a viewbag or even a viewmodel when you just want to show one line of static text? You usually don't use a calculator if you want to add 2 + 2, do you?

<div>

seems fine to me at this

+1


source







All Articles