c# - 我们如何使用 LINQ 从 asp.net mvc3 中的长字符串中提取短字符串?

标签 c# asp.net-mvc string linq

我目前正在从事一个小型电子商务项目。我想显示产品的简短描述,而不是显示所有描述(来自数据库)。
这是我的 Controller ;

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

这是我的 View 代码;

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

现在在我的部分 "_ProductPartial" View 中,我有一个名为的描述字段;

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

现在,我想显示产品的简短描述(而不是显示默认情况下的完整描述)。
那么,我如何使用 LINQ 执行此操作?
有没有其他方法(如果可能的话)?

最佳答案

我正在使用 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 类来拥有这个只读属性

关于c# - 我们如何使用 LINQ 从 asp.net mvc3 中的长字符串中提取短字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11062065/

相关文章:

c# - SqlConnection 为 NULL 的可能原因

c# - 如何根据当前日期时间发现财政年度?

c# - 在 IronPython 中访问 C# 类成员

asp.net-mvc - MVC RouteLink 中的 HTML

asp.net-mvc - Controller 运行之前是否有事件发生?

string - 在 R 中以 "V, W, X, Y, and Z"样式输出列表的简单方法

c# - RichTextBox 中的居中对齐段落

asp.net-mvc - ASP.NET MVC+ELMAH - 发生异常时 Controller 方法需要很长时间才能响应

php - 替换所有字符直到反斜杠n次

java - 获取用户输入并将其分配给对象