3

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

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I dont have a problem with my truncate its only that I want to truncate the text inside the texteditor. But +1 for presenting me another method how to do it.. :)
I would have to agree that having the business logic in the model is definitely better than in the view.
2

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)

1 Comment

cool I'm trying ssilas777 suggestions but your answer works faster. thanks. That answers it.. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.