bot
bot

Reputation: 4911

Truncate model property in ASP.Net MVC

Im currently using a truncate and texteditor in different way. And both is working fine but I facing this problem. I want to truncate a text inside the texteditor. T_T

Im using truncate this way and its working

@helper Truncate(string input, int length)
    {
    if (input.Length <= length)
    {
        @input
    }
    else
    {
        @input.Substring(0, length)<text>...</text>
    }
}


@foreach (var item in Model)
{       
        <div>
            @Truncate(item.DetailDescription, 400)
        </div>
}


AND

Im declaring raw to call a texteditor this way and its also working fine

@html.Raw(item.DetailDescription)


PROBLEM: How could I possibly combine the two in a single function? Is this even possible T_T

Upvotes: 3

Views: 3477

Answers (2)

ssilas777
ssilas777

Reputation: 9804

It's always better to put the business logic inside the model.

I would have done this in the model itself adding another property 'TruncatedDescription'.

  public string TruncatedDescription
    {
        get
        {
            return this.DetailDescription.Length > 400 ? this.DetailDescription.Substring(0, 400) + "..." : this.DetailDescription;
        }
    }

So you can use this in the View directly

@foreach (var item in Model)
{       
        <div>
             item.TruncatedDescription
        </div>
}

If you are following this method, you can use item.TruncatedDescription in the text-editor with out help of html.Row as this won't be HTML encoded.

Upvotes: 6

user2067192
user2067192

Reputation:

I've done like this one before. I did it this way.

@helper Truncate(string input, int length)
 {
   if (input.Length <= length) {
   @Html.Raw(input)
    } else {
    var thisString = input.Substring(0, length);
    @Html.Raw(thisString)
            }
 }

I combined raw inside the truncate helper then I call the Truncate this way

@Truncate(item.DetailDescription, 400)

Upvotes: 2

Related Questions