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:
And after click:
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:
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.
What u have written make no sense at all.
Did you see the project?
I am ready to modify the blog – english is not my native language. Please suggest.
Hey Andrei, thanks for posting this, I have implemented this in my mvc3 web sites – good job.
Thank you. And glad to help!