【问题标题】:Passing object to view error传递对象以查看错误
【发布时间】:2011-09-01 03:37:05
【问题描述】:

尝试将我的对象传递给视图时出现此错误。我是 MVC 的新手,所以请原谅我。 传入字典的模型项的类型为 'System.Collections.Generic.List1[<>f__AnonymousType13[System.Int32,System.String,System.Nullable1[System.DateTime]]]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[MvcApplication1.Models.storageProperty]'

我正在尝试传递一个表的列表,该表将显示 storageProperty 表中的对象以及费用表中的最后日期(如果有的话)。大多数物业至少进行过一次费用审计,有些进行了多次审计,而另一些则没有。 这是控制器的代码:

var viewModel = db.storageProperties.Select(s => new
        {
            s.storagePropertyId,
            s.BuildName,
            latestExpenseSurvey = (DateTime?)s.expenses.Max(e => e.expenseDate)
        }).ToList();
        return View(viewModel); 

         }

并且视图中的@model 语句需要一个 storageproperty 对象。我正在将 mvc3 与实体框架一起使用。很明显,我不能传递这个列表对象来代替 storageproperty 对象,但我不知道该怎么做,我应该怎么做?

提前致谢。

【问题讨论】:

    标签: c# asp.net-mvc-3


    【解决方案1】:

    永远不要将匿名对象传递给视图。您应该始终传递视图模型。

    因此,在 ASP.NET MVC 应用程序中,您首先要定义一个反映您的视图要求的视图模型:

    public class MyViewModel
    {
        public int StoragePropertyId { get; set; }
        public string BuildName { get; set; }
        public DateTime? latestExpenseSurvey { get; set; }
    }
    

    然后在你的控制器中返回一个IEnumerable<MyViewModel>:

    public ActionResult Index()
    {
        var viewModel = db.storageProperties.Select(s => new MyViewModel
        {
            StoragePropertyId = s.storagePropertyId,
            BuildName = s.BuildName,
            LatestExpenseSurvey = (DateTime?)s.expenses.Max(e => e.expenseDate)
        }).ToList();
        return View(viewModel); 
    }
    

    最后将您的视图强输入到此视图模型的集合中:

    @model IEnumerable<MyViewModel>
    <div>
        @Html.EditorForModel()
    </div>
    

    【讨论】:

      【解决方案2】:

      您的 Linq 查询项目为匿名类型。您需要为此投影创建一个命名类型,以便从视图中引用它。

      【讨论】:

        猜你喜欢
        • 2014-09-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-31
        • 1970-01-01
        • 2011-03-19
        • 1970-01-01
        相关资源
        最近更新 更多