我们如何使用LINQ从asp.net mvc3中的长字符串中获取一个短字符串?

时间:2012-06-16 08:55:18

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

我目前正在开展一个小型电子商务项目。我想显示产品的小描述,而不是显示所有描述(从数据库中提交)。
这是我的控制器;

var products = context.Products.OrderBy(p => p.ProductName);
@ViewBag.ProductList = products.ToList<Product>();

这是我的观看代码;

<ul class="display" id="content">
@foreach( var item in @ViewBag.ProductList as IEnumerable<Product>)
{
    @Html.Partial("_ProductPartial", item)
}
</ul>

现在在我的部分“_ ProductPartial”视图中,我有一个名为的描述字段;

<p>
    @Html.DisplayFor(model => model.ProductDescription)
</p>

现在,我想显示产品的简短描述(而不是显示默认情况下的整个描述)。
那么,我如何使用LINQ做到这一点?
还有其他方式(如果可能)吗?

1 个答案:

答案 0 :(得分:7)

我是通过使用ViewModel来实现的:

    public string ProductDescription { get; set; }

    public string ShortDescription
    {
        get
        {
            var text = ProductDescription;
            if (text.Length > 21)
            {
                text = text.Remove(19);
                text += "..";
            }
            return text ;
        }
    }

如果您不想制作ViewModel,可以将Product类扩展为具有此只读属性