C# 在模型上为一个字段添加子字符串并发送到视图

C# 在模型上为一个字段添加子字符串并发送到视图,c#,model-view-controller,model,C#,Model View Controller,Model,我有一个模型,我在这个模型上发送子字符串一个字段,然后返回到一个视图,以便在gridview中显示 我的模型是: public class News { public int ID { get; set; } [MaxLength(300)] public string Title { get; set; } [DataType(DataType.MultilineText)] [MaxLength] public string Conten

我有一个模型,我在这个模型上发送子字符串一个字段,然后返回到一个视图,以便在gridview中显示 我的模型是:

public class News
{

    public int ID { get; set; }

    [MaxLength(300)]
    public string Title { get; set; }

    [DataType(DataType.MultilineText)]
    [MaxLength]
    public string Content { get; set; }

    [ReadOnly(true)]
    public DateTime Date { get; set; }

    [Column("PictureID")]
    public virtual Picture Picture { get; set; }
    //public IList<Picture> PicID { get; set; }

    [Column("NewsTypeID",Order=1)]
    public virtual NewsType NewsType { get; set; }

    public ICollection<Tag> Tags { get; set; }


    public News()
    {
        Tags = new List<Tag>();
    }
}
它正常,并在gridview中正确显示

但如果通过控制器中的此cod发送此模型:

public ActionResult ShowNews()
    {
        var data = new DatabaseContext();
        var news = data.newsInfo.ToList();
        return View(news);
    }
public ActionResult ShowNews()
    {

        var data = new DatabaseContext();
        var news = data.newsInfo.Select(x => new { Content = x.Content.Substring(0,200), x }).ToList();
        return View(news);
    }
显示此错误:

传递到字典中的模型项的类型为“System.Collections.Generic.List
1[f_uAnonymousType0
2[System.String,Newsagence.Models.News]]”,但此字典需要类型为“System.Collections.Generic.List`1[Newsagence.Models.News]”的模型项

我已发送字段的子字符串之一


问题出在哪里?

您已在此语句中创建匿名对象列表:

data.newsInfo.Select(x => new { Content = x.Content.Substring(0,200), x }).ToList();
您已将其作为模型发送到视图:

View(news);
但是,在您的视图中,您已将模型类型设置为
List
。因此,例外情况被抛出。尝试将代码更改为:

var news = data.newsInfo.AsEnumerable().Select(x => { x.Content = x.Content.Substring(0,200); return x; }).ToList();

如果要将整个
内容
值与子字符串一起发送,然后,我建议使用第一种方法,并使用razor inside view获取所有项目的
内容的子字符串。

我测试了您的Cod,但这不是真的。请在Cod中显示错误:带有station body的lambda表达式无法转换为表达式tree@amirseydilo编译器错误还是运行时错误?还有错误是什么?@amirseydilo能否复制并粘贴到此处异常消息?具有语句正文的lambda表达式无法转换为表达式tree@amirseydilo我用
AsEnumerable()更新代码