【问题标题】:How can I truncate a string using MVC Html Helpers?如何使用 MVC Html Helpers 截断字符串?
【发布时间】:2014-06-27 16:00:26
【问题描述】:

我正在尝试截断一个长字符串以仅在我的索引页面上显示。如下所示:

<td>
    @Html.DisplayFor(modelItem => item.Description)
</td>

描述可以有 500 个字符长,但我不能在那个网格布局上显示那么多。我想只显示前 25 个,因为他们可以在详细信息页面上看到所有这些,但如果不在模型级别截断它,我似乎无法让它工作。

这样的东西会很好:

@Html.DisplayFor(modelItem => item.Description.Take(25))
@Html.DisplayFor(modelItem => item.Description.Substring(0,25)

编辑

当我尝试任一方法时,我在运行时遇到以下异常。

Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.

【问题讨论】:

  • 您是否考虑过创建一个额外的模型属性来执行子字符串并使用它?
  • 是的,如果没有办法使用模板和单个属性,我就是这样做的。
  • 您的具体问题是传递给Html.DisplayFor 的表达式必须引用实际属性,而不是特定值。换句话说,你只能做@Html.DisplayFor(m =&gt; item.Description),不能做@Html.DisplayFor(m =&gt; item.Description.Substring(0, 25))。不过,您不需要为此使用Html.DisplayFor,因此您只需编写@item.Description.Substring(0, 25)。但是,请记住@48klocs 对 Nathan A 的回答的评论。
  • 请注意,Take() 返回一个IEnumerable&lt;char&gt;,而不是一个字符串。 Substring() 更适合这个。

标签: c# .net asp.net-mvc


【解决方案1】:

不要使用 html 帮助器。只需这样做:

@item.Description.Substring(0, Math.Min(item.Description.Length, 25));

我假设你在某个循环中,item 是当前元素。

【讨论】:

  • 如果字符串不超过 25 个字符,则会抛出 ArgumentOutOfRangeException
  • @NathanA ,这很好用,但是您能否提供选项 2 以在末尾显示点,例如 mydescription ..... ,我尝试了 this 并在解析时出错,您有什么想法吗?
  • @NathanA 非常感谢。我一直在努力解决这个问题,因为 2 小时终于得到了解决方案
【解决方案2】:

您可以使用扩展方法来做到这一点。

public static string Truncate(this string source, int length)
{
    if (source.Length > length)
    {
        source = source.Substring(0, length);
    }

    return source;
}

那么在你看来:

@item.Description.Truncate(25)

【讨论】:

  • 那仍然行不通。 DisplayFor 仅接受产生值的表达式(特别是错误中列出的内容),而不接受方法调用。这就是产生 Templates 错误的原因。
  • @NathanA 你可能是对的。我没有检查DisplayForDisplay 的调用是什么。我认为一个名为 Display 的元素应该可以工作,但我只是在猜测。
  • 看起来更好。良好的通用应用程序。
【解决方案3】:

你可以在数据到达视图之前截断数据,或者使用这个 Razor:

@{
    var shortDescript = String.Concat(modelItem.Take(25));
}
@Html.DisplayFor(modelItem => shortDescript)

【讨论】:

  • 虽然这可能行得通,但你为什么还要使用DisplayFor 呢?这样做会失去在数据模型成员上使用它所获得的任何好处。
  • 假设类型没有改变(字符串到字符串),您仍然可以使用相同的显示模板。见stackoverflow.com/a/6365658/1445356
【解决方案4】:

您可以考虑为您需要的此类实例创建一个特殊的模型属性:

public class MyModel
{
    public string MyDescription {get; set;}
    public string MyShortDescription {
        get 
        {
              return Truncate(MyDescription, 25);
        }
}

private string Truncate(string, howMany)
{
   // Code to perform the substring here
}

@Html.DisplayFor(modelItem => item.MyShortDescription);

【讨论】:

    【解决方案5】:

    试试这个如果你想使用 HTML 帮助器。假设您想在第一个空格 .IndexOf(' ') 之前获取字符串的一部分(或者您可以像您说的那样使用预定义的索引 25):

    @Html.DisplayFor(modelItem => item.Description).ToString().Substring(0,item.Description.IndexOf(' '))
    

    【讨论】:

      【解决方案6】:

      ASP Net Core 3 MVC 的 HTML 助手。

      public static HtmlString Truncate(this IHtmlHelper helper, string text, int maxLength = 100)
      {
          if (text == null) return new HtmlString("");
      
          if (text.Length > maxLength)
          {
              text = text.Substring(0, maxLength) + "...";
          }
          return new HtmlString($"{text}");
      }
      

      在cshtml文件中使用

      @Html.Truncate(item.Description)
      

      或者你可以使用参数

      @Html.Truncate(item.MusicUrl, 50)
      

      【讨论】:

        【解决方案7】:

        尝试扩展

        public static string TruncateMiddle(this string value, int lengthExpected, string separator = "...")
            {
                if (value.Length <= lengthExpected) return value;
        
                decimal sepLen = separator.Length;
                decimal charsToShow = lengthExpected - sepLen;
                decimal frontChars = Math.Ceiling(charsToShow / 2);
                decimal backChars = Math.Floor(charsToShow / 2);
        
                return value.Substring(0, (int)frontChars) + separator + value.Substring(value.Length - (int)backChars);            
            }
        

        使用

        MyLongString.TruncateMiddle(50)
        

        返回如下内容:Lorem ipsum dolor sit ame...onsectetur cras amet。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-04-18
          • 2013-02-15
          • 2016-12-22
          • 1970-01-01
          • 1970-01-01
          • 2011-02-16
          • 1970-01-01
          相关资源
          最近更新 更多