Call Razor CSHTML IF

Can anybody help me? I have the following code:

@inherits umbraco.MacroEngines.DynamicNodeContext
@{ 
    var node = @Model.NodeById(1257);
}
    <div class="Top10"> 
    <h1>Newest</h1>

@foreach (var article in node.Descendants().Where("Visible && (NodeTypeAlias = \"Article\" || NodeTypeAlias = \"sergrein\" || NodeTypeAlias = \"solomyndagrein\")").OrderBy("createDate desc").Take(10))
    {                   
         <a href="@article.Url"><h2>@article.createDate.ToString("dd/MM") | @article.title</h2></a>    
    }

    </div>

I want: if @ article.title is more than, for example, 10 characters, it needs to return 10 characters, followed by ... (for example: "this_is_a _..."). If the character @ article.title is shorter than 10 characters, it can simply show the full length of the title. How can this truncation be done?

+4
source share
3 answers

try it

@(article.title.Length > 10 ? (article.title.Substring(0,10) + " ...") : article.title)
+3
source

Normally I would say do it in your model, but it looks like you are using the Umbraco model.

So you can just do:

@inherits umbraco.MacroEngines.DynamicNodeContext
@{ 
    var node = @Model.NodeById(1257);
}
<div class="Top10"> 
<h1>Newest</h1>

@foreach (var article in node.Descendants().Where("Visible && (NodeTypeAlias = \"Article\" || NodeTypeAlias = \"sergrein\" || NodeTypeAlias = \"solomyndagrein\")").OrderBy("createDate desc").Take(10))
{                
    {
        var title = article.title;
        if (title.Length > 10)
            title = title.Substring(0,10) + "...";
    }
    <a href="@article.Url"><h2>@article.createDate.ToString("dd/MMM") | @title</h2></a>    
}

</div>
+1
source

,

@{
if(article.title.ToString().Length > 10)
 {
  article.title = article.title.Substring(0,10) + " ..."; //the format you desire
 }
 else
 {
  article.title; // default
 }
 }
+1

All Articles