String Truncate in MVC

I always wanted a string truncate  – i.e.,if you have a long string,to have “show less” and “show more”.

So I have decided to do it .

1. See in action first:

image

And after click:

image

2. How can you use in your MVC projects:

Add in your project the \Views\Shared\DisplayTemplates\StringTruncate.cshtml file ( in this folder!) and put
@Html.DisplayFor(m => m.String1,”StringTruncate”)

3. Code: It implies only a div and a hidden – and javascript,of course.

@model string

@{
    string id = ViewData.ModelMetadata.PropertyName;
   string textFull = Html.Encode(Model??"");
   string PartialText = textFull;
   string less = "";
   bool full = true;
   if (PartialText.Length > 20)
   {
       full = false;
       PartialText = PartialText.Substring(0,20) + "...<a href=javascript:showHide_" + id + "(true)>(more)</a>";
   }

   }

<div title="@textFull" id='@("display"+ id)'>
        @Html.Raw(PartialText )

    </div>
    @{if (full) {
          return;
      }
     }

<div  id='@("hid" + id)' style="display:none">
@textFull
<p><a href='javascript:@("showHide_"+ id) (false)'>less</a></p>
</div>
<script type="text/javascript">
function @("showHide_"+ id) (showFull){

$("#@("display"+ id)").toggle(!showFull);

$("#@("hid"+ id)").toggle(showFull);

}
</script>

4. Source code here:

string Truncate

5. TODO ( homework):

Modify the source in order to have one javascript and send the ids of the hidden and of the div to the function.


Posted

in

by

Tags:

Comments

4 responses to “String Truncate in MVC”

  1. Adam Avatar
    Adam

    What u have written make no sense at all.

    1. Andrei Ignat Avatar
      Andrei Ignat

      Did you see the project?
      I am ready to modify the blog – english is not my native language. Please suggest.

  2. Darren Avatar
    Darren

    Hey Andrei, thanks for posting this, I have implemented this in my mvc3 web sites – good job.

    1. Andrei Ignat Avatar
      Andrei Ignat

      Thank you. And glad to help!

Leave a Reply

Your email address will not be published. Required fields are marked *