Let me start with: I am n00b on ASP.NET MVC. I like it, but I'm n00b.
I am trying to pass "complex" data from a LINQ query. I understand how to use the data context, and then just throw that data when I submit it, but when I make a more complex LINQ query that returns an anonymous type, everything breaks.
I saw someone ask a similar question ( MVC LINQ to SQL Table Join Record Display ), and the answer seemed to be to create a new data type to capture data from a LINQ query. I don’t understand that I can create the var type in the controller and access the member fields in the controller, but if I want to pass this var back to my view, I need to create an entire new class for it.
Here is my controller code:
var vrGoodResults1 = from records in db.Words
group records by records.word1 into g
select new
{
strWord = g.Key,
intWordCount = g.Count()
};
ViewData["GoodWords"] = vrGoodResults1;
return View();
And the view looks like this:
<% foreach (var kvp in (IEnumerable)ViewData["GoodWords"]) %>
<% { %>
<%= String.Format("{0} was used times", kvp) %> <br />
<% } %>
What outputs:
{strWord = cool, intWordCount = 2 } was used times
{strWord = educated, intWordCount = 1 } was used times
{strWord = great, intWordCount = 1 } was used times
{strWord = smart, intWordCount = 6 } was used times
{strWord = strong, intWordCount = 2 } was used times
{strWord = super smart, intWordCount = 2 } was used times
So, the data falls into the view, but I can not refer to the data by the field names that I assigned in the LINQ query. When I try to reset kvp.GetType (), I get:
<>f__AnonymousType1`2[System.String,System.Int32]
All I want to do is something like:
<%= String.Format("{0} was used {1} times", kvp.strWord, kvp.intWordCount) %> <br />
But I get a compilation error on kvp.strWord.
error CS1061: 'object' does not contain a definition for 'strWord' and no extension method 'strWord' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)
If I paste the following code into my controller:
foreach (var kvp in vrGoodResults1)
{
string strNew = kvp.strWord;
}
I can refer to the fields of my kvp variable without a compilation error. So something is lost when switching from a controller to a view. Am I forgetting to turn something on? Perhaps the "use" or in the "<@Page" directive, I forget to inherit something?
LINQ , IEnumerable < "datatype" > "datatype" = , . - LINQ, , - , .