nikhil
nikhil

Reputation: 1736

Truncate string text using jQuery

I have a Razor view Html.DisplayFor where I am displaying some text. Now I want to truncate the text using jQuery. I am using the jQuery code from this jQuery Truncate.

In my csHtml, I have something like follows, the BlogContent is some string that I am Binding. Of course I think I can do SubString etc in C# on the BlogContent to truncate. But I want to do it using jQuery. I have tried the below code but no luck.

@{ 
    Layout = null;
}

      <div class="blog-post-body">
    <p class="p-bottom-20">@Html.DisplayFor(modelItem => item.BlogContent)</p>
     </div>
    
    @section scripts
    {
    <script src="~/js/jquery.min.js"></script>
    
            <!-- Bootstrap -->
            <script src="~/bootstrap/js/bootstrap.min.js"></script>
    
     <script>
                $(document).ready(function () {
                    $('ul.pagination > li.disabled > a').addClass('page-link');
                    truncateText(".p-bottom-20", 100);
                });
    
                function truncateText(selector, maxLength) {
                    $(selector).text((i, txt) => txt.length > maxLength ? txt.substr(0, maxLength) + "..." : txt);
                };
    
            </script>
    
    }

I don't see any errors on the Browser Console related to this.

No console errors

Upvotes: 2

Views: 139

Answers (1)

Dimitris Maragkos
Dimitris Maragkos

Reputation: 11312

If you are using Layout = null; then @section Scripts doesn't work because the section is defined in _Layout.cshtml. You have to add a full html document in your view.

@{
    Layout = null;
}

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>title</title>
  </head>
  <body>
    <div class="blog-post-body">
      <p class="p-bottom-20">@Html.DisplayFor(modelItem => item.BlogContent)</p>
    </div>

    <script src="~/js/jquery.min.js"></script>
    <script src="~/bootstrap/js/bootstrap.min.js"></script>
    
    <script>
      $(document).ready(function() {
        $('ul.pagination > li.disabled > a').addClass('page-link');
        truncateText(".p-bottom-20", 100);
      });

      function truncateText(selector, maxLength) {
        $(selector).text((i, txt) => txt.length > maxLength ? txt.substr(0, maxLength) + "..." : txt);
      }
    </script>
  </body>
</html>

Upvotes: 1

Related Questions