0

I very new to .NET and Entity Framework, and I have a problem with my code (below). I am getting the following error:

        Unable to cast object of type '<>f__AnonymousType1`2[ 
    SamWinInterface.Models.tbl_interface_category,
    SamWinInterface.Models.tbl_interface_menu]' to type
'SamWinInterface.Models.tbl_interface_menu'.

This is my code:

public ActionResult Index(int id=-1)
{
    ViewBag.Menus = from menu in _db.tbl_interface_menu 
                    join cat in _db.tbl_interface_category on 
                    menu.fld_category_id equals cat.id where 
                    cat.fld_customer_id == id select new { cat, menu }; 

    return View();
}

I'm trying to get menus depending on which category is chosen.

Something like:

<% foreach (tbl_interface_menu m in (IEnumerable)ViewBag.Menus)
   { %>

    <%=  m.fld_section2_title %>

<% } %> 

but I'm getting the above error. How can I get the menus?

tereško
  • 58,060
  • 25
  • 98
  • 150
Altin
  • 2,175
  • 3
  • 25
  • 47

2 Answers2

1

You cannot pass anonymous objects to views. This doesn't work because anonymous types are emitted as internal. And because ASP.NET views are compiled into a separate assembly at runtime they cannot access those times because they reside in a different assembly. This basically means that an anonymous object that you have defined in your controller action cannot be accessed in your view.

So as always in an ASP.NET MVC application start by defining view a model:

public class MyViewModel
{
    public Category Category { get; set; }
    public Menu Menu { get; set; }
}

then have your controller action fill this view model and pass it to the view:

public ActionResult Index(int id=-1)
{
    var model = 
        from menu in _db.tbl_interface_menu 
        join cat in _db.tbl_interface_category 
        on menu.fld_category_id equals cat.id 
        where cat.fld_customer_id == id 
        select new MyViewModel { Category = cat, Menu = menu }; 

    return View(model);
}

and finally have a strongly typed view:

<%@ Page 
    Language="C#" 
    MasterPageFile="~/Views/Shared/Site.Master" 
    Inherits="System.Web.Mvc.ViewPage<IEnumerable<AppName.Models.MyViewModel>>" 
%>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

<% foreach (var item in Model) { %>
    <%= item.Menu.fld_section2_title %>
<% } %>

</asp:Content>
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
0

As Darin said, you cannot pass anonymous types to views, but you could convert them to Expando objects, and that would prevent you from having to define viewmodels.

Personally I would probably just define viewmodels, but this option is handy in a pinch.

Community
  • 1
  • 1
Brook
  • 5,949
  • 3
  • 31
  • 45