开发者

ASP.Net MVC ViewData Issue

开发者 https://www.devze.com 2023-02-20 11:53 出处:网络
I have the following code: private Models.mediamanagerEntities dataModel =开发者_如何学Python new Models.mediamanagerEntities();

I have the following code:

private Models.mediamanagerEntities dataModel =开发者_如何学Python new Models.mediamanagerEntities();

public ActionResult Index(FormCollection form)
{
    ViewData.Model = (from m in dataModel.Customers select m.Type.Items).ToList();
    return View();
}



View:

%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<List<Project_Name.Models.Item>>" %>

<% foreach (var m in ViewData.Model)
   { %>

    Title: <%= m.Title %>
    <% } %>

I get the following error:

The model item passed into the dictionary is of type 'System.Collections.Generic.List1[System.Data.Objects.DataClasses.EntityCollection1[Project_Name.Models.Item]]', but this dictionary requires a model item of type 'System.Collections.Generic.List`1[Project_Name.Models.Item].

I'm not too sure what it happening here or how to rectify it, Thanks.


Your LINQ is creating a list like this List<EntityCollection<Item>>, when your view wants List<Item>.

I don't know query syntax for LINQ very well, but this is how you'd get what you want with function syntax:

ViewData.Model = dataModel.Customers.SelectMany(c => c.Type.Items).ToList();

That will take the many Items under each customer and flatten them into one list of Items.


Replace this line:

ViewData.Model = (from m in dataModel.Customers select m.Type.Items).ToList();

with the following:

 ViewData.Model = dataModel.Type.ToList();
0

精彩评论

暂无评论...
验证码 换一张
取 消