c# – how to access new manuplated combined columns in MVC asp.net using linq – Education Career Blog

I am facing problem in displaying the column field value at the view.

I am returning view like follows.

var TicketList = (from T in db.Tickets
                  where  T.Title.Contains("a")
                  select new {
                        customerName = (
                             from cname in db.Customers
                             where cname.CustomerId == T.CustomersId
                             select cname.FirstName + cname.LastName
                        ) ,
                        Title = T.Title
                  }).ToList();

 return View("SearchTicketsResult",TicketList);

and at the view page I have

<%foreach (TicketList ti in (IEnumerable)ViewData.Model) {%>
    <%=ti.Title%><br />
    <%=ti.customerName %>
<% } %>

I am not able to list customername or the title in the page. It says “The type or namespace name ‘TicketList’ could not be found (are you missing a using directive or an assembly reference?)”

Can someone guide me please.

Thanks in advance.

,

“TicketList” is the variable name for a list of an anonymous type. There is no “TicketList” type. Casting from anonymous types can be done (“by example”), but is very brittle, and I simply don’t recommend you use an anonymous type for this.

One option would be to declare my own type (in the UI’s “model(s)” folder) – for example TicketSummary / TicketLite (etc), with a Title and CustomerName. Then use this type:

public class TicketSummary
{

     public string CustomerName { get; set; }
     public string Title { get; set; }
}

var ticketList = (from t in db.Tickets
                  where  t.Title.Contains("a")
                  select new TicketSummary
                  {
                      CustomerName = (
                          from cname in db.Customers
                          where cname.CustomerId == t.CustomersId
                          select cname.FirstName.ToString()
                      ).FirstOrDefault(),
                      Title = t.Title
                  }).ToList();
return ticketList;

Then you should be able to use:

<%foreach (TicketSummary ts in (IEnumerable<TicketSummary>)ViewData.Model) {%>
    <%=ts.Title%><br />
    <%=ts.customerName %>
<% } %>

In reality, I’d probably offload this work to a repository, and have a repository method that returns a list of the summary type.

Leave a Comment