Best practice for graphical if-statments in MVC 3

Just started converting to MVC from the classic ASP and wondered about best practice for if statements that are used to determine whether an HTML element should be visible or decide whether an HTML element should be visible.

Example:

if (type = 1)
{
    <img src="/Content/Images/gray.jpg" />
}
else
{
    <img src="/Content/Images/blue.jpg" />
}

Here I see several options.
1. Use if-statements in my views (prefer not to use)
2. Use an HTML helper (there will be many helpers = Hard to work with the code)
3. Create HTML snippets in my controller and go to my view
4. Working with JavaScript for show / hide an element when loading a document.

, , , . !
/Mike

EDIT: , :

if (type = 1)
{
    <span class="class1">Something something</span>
}
else
{
    <div id="id1">
        text 
        <img src="/Content/Images/gray.jpg" />
    </div>
}
+3
2

HtmlHelper HTML- , . , , :

<img src="/Content/Images/@(i == 1 ? "gray" : "blue").jpg" />

, , HTML. Razor, , ~/Views/Helpers. , .

, . , . IfOneThenShowSomethingElseGrayImage, .

, , - . :

@helper UserType(int type) {
   @if (type == 1) {
    <span class="class1">Something something</span>
   } else {
    <div id="id1">
        text 
        <img src="/Content/Images/gray.jpg" />
    </div>
   }    
}

:

@UserType(Model.UserType)

, , .

.

+1

viewmodels html.

 public class ViewModel
 {
     public string ImageName { get; set; }
 }

:

<img src="/Content/Images/<%= Model.ImageName %>.jpg" />
+3
source

Source: https://habr.com/ru/post/1794437/


All Articles