效果如下:

ASP.NET MVC中页面中进行自定义文字截取

其实截取方法跟aspx页面中一样,不管是用C#还是js或者CSS都可以实现,

我在这里只是想记录在MVC中怎么用的两种方法:

方法一:

先新建一个类

ASP.NET MVC中页面中进行自定义文字截取

然后编写以下方法:

public static class HtmlHelpers
{
public static string Truncate(this HtmlHelper helper, string input, int length)
{
if (input.Length <= length)
{
return input;
}
else
{
return input.Substring(0, length) + "...";
}
}
}

在web.config中此处进行注册

ASP.NET MVC中页面中进行自定义文字截取

添加以下信息:

<add namespace="(your solutionname).Helpers"/>

最后就是在View页面中用了:

<%: Html.Truncate(item.Title, 25) %> (MVC2写法)

@Html.Truncate(item.Artist.Name, 25) (MVC3写法)

方法二(MVC3):

直接在View页面中:

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

然后调用这个方法:

@Truncate(item.Artist.Name, 25)

相关文章:

  • 2021-12-04
  • 2022-12-23
  • 2021-11-03
  • 2022-02-25
  • 2022-12-23
  • 2021-07-08
  • 2021-09-02
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-25
  • 2021-09-06
  • 2021-05-20
  • 2021-06-23
相关资源
相似解决方案