关于c#:需要截断Razor HTML DisplayFor Helper

Need to truncate Razor HTML DisplayFor Helper

我试图截断有时很大的文本字段,或者在其他时候截断数据库中的null,即

1
@Html.DisplayFor(modelItem => item.MainBiography)

并在末尾替换为三个点。

我已经尝试了substring函数,但一直收到错误消息。

任何指针,谢谢!

更新:

...不是很重要,所以我尝试使用

1
 @Html.DisplayFor(modelItem => item.MainBiography.Substring(0,10))

并获得以下错误代码:

System.InvalidOperationException was unhandled by user code HResult=-2146233079 Message=Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions. Source=System.Web.Mvc –


最好在模型中创建另一个属性,以拾取MainBiography并最终将其缩短。

像这样:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// This is your property (sampled)
public string MainBiography { get; set; }

//How long do you want your property to be at most ?
//(Best practice advices against magic numbers)
private int MainBiographyLimit = 100;

//You probably need this if you want to use .LabelFor()
//and let this property mimic the"full" one  
[Display(Name="Main Biography")]
public string MainBiographyTrimmed
{
    get
    {
        if (this.MainBiography.Length > this.MainBiographyLimit)
            return this.MainBiography.Substring(0, this.MainBiographyLimit) +"...";
        else
            return this.MainBiography;
    }
}

用法是

1
@Html.DisplayFor(item => item.MainBiographyTrimmed)

另一种方法是建立一个完整的视图模型,但是我发现它常常是过大的。


DisplayFor需要一个表示属性的表达式。

您可以向模型添加属性:

1
2
3
4
5
6
7
8
public string MainBiographyTrimmed
{
    get
    {
        if (MainBiography.Length) > 10
            return MainBiography.Substring(0, 10) +"...";
    }
}

然后在您看来只需执行以下操作:

1
@Html.DisplayFor(item => item.MainBiographyTrimmed)

您可以编写一个字符串扩展方法,然后在您的model属性(字符串类型)上调用它。您可以为子字符串操作传递限制。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public static class StringExtensions
{
    public static string SubStringTo(this string thatString, int limit)
    {
        if (!String.IsNullOrEmpty(thatString))
        {
            if (thatString.Length > limit)
            {
                return thatString.Substring(0, limit);
            }
            return thatString;
        }
        return string.empty;
    }
}

然后在您的视图中,导入具有扩展方法的名称空间,并在string属性上调用该方法。

1
@Html.DisplayFor(modelItem => item.MainBiography.SubStringTo(10))

尝试使用Html.Display代替DisplayFor,如下所示:

1
 @Html.Display(item.MainBiography.Substring(0, 10), null,"MainBiography")

顺便说一下,您的两个lambda语句均无效。参数名称应相同。

不是这样的:

1
@Html.DisplayFor(modelItem => item.MainBiography)

它应该是:

1
@Html.DisplayFor(modelItem => modelItem.MainBiography)

要么:

1
@Html.DisplayFor(item => item.MainBiography)