开发者

MVC.net razor substring in view problem

I am having a problem with razor and models.

In my view I have a model with a list with "article" objects.

So I do a foreach with @MvcHtmlString.Create(article.Intro) which works great.

Then when I want a substring of that intro:

@MvcHtmlString.Create(article.Intro).ToHtmlString().Substring(0, 50) the page ends in endless loop (which happens often when razor can't render something) without an error.开发者_如何学Go

Does anyone know how I can get this substring ?


Substring(0, 50) throws an ArgumentOutOfRangeException exception if any of your article intros is shorter than 50 characters. That's probably the cause of your strange problem.

Furthermore, the use of MvcHtmlString is incorrect since your data obviously isn't HTML encoded yet.

So a solution could be:

@article.Intro.Substring(0, Math.Min(article.Intro.Length, 50))


Why not simply substring your article.Intro directly?

@MvcHtmlString.Create(article.Intro.Substring(0, 50))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜