当前位置: 动力学知识库 > 问答 > 编程问答 >

asp.net mvc - 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.

Does anyone know how I can get this substring ?

网友答案:

Why not simply substring your article.Intro directly?

@MvcHtmlString.Create(article.Intro.Substring(0, 50))
网友答案:

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))
分享给朋友:
您可能感兴趣的文章:
随机阅读: