MVC :: Runtime Binder Exception When Using Anonymous Type In Untyped View?

Aug 14, 2010

I'm using MVC, and in the controller, I'm using a linq to objects query which returns an anonymous type:

var results = from ... select new { ... };

I then pass this information to an untyped view:

return View(results);

I try to iterate through the data in the view:

<% foreach (var entry in Model)%>

...

<%: Html.Encode(entry.MyProperty) %>

However, I get a RuntimeBinderException: 'object' does not contain a definition for 'MyProperty'. However, oddly, if I hover above entry with the mouse, it does actually have MyProperty in the popup window, and the value is what I would expect,(apparently, the Visual Studio IDE knows what type it is).I can get around this problem by using a linq query which uses an explicit type and a parameterless constructor of the form:

IQueryable<SearchResult> results = from ... select new SearchResult { ... };

and creating a view model class which encapsulates the SearchResult data, which is then returned to a strongly typed view. However, I don't understand what the problem is with the first method.

View 9 Replies


Similar Messages:

MVC :: To Add A Strongly Typed View For An Anonymous Type [Newbie]?

Jan 25, 2011

I have controller method that looks something like this:

[Code]....

notice the commented out line. This method used to return an IEnumerable<Sport> but now that I have used a LINQ query it is returning an IEnumerable of an anonymous type (I think that's the correct terminology - please correct me if I'm wrong).

Question I have is...can I add a strongly-typed view based on this anonymous type and if not, how do I write a view that can access this collection?

View 3 Replies

C# And Anonymous Types - Iterate Through A DataTable While Manually Building An Anonymous Type

Jan 18, 2010

I am currently implementing a client-side paging solution using ASP.NET, jQuery and JSON.

I have been following the excellent article from encosia: http://encosia.com/2008/08/20/easily-build-powerful-client-side-ajax-paging-using-jquery/

In my Web Method I retrieve my data from the database as a DataTable:

DataTable categoryProducts = ProductViewerAccess.GetCategoryProducts
("AA", 4, 0, Page.ToString(), out howManyPages, "FALSE", 0, "CostPrice", "asc", destinationList);

I then retrieve the data from the DataTable into an anonymous type:

var feeds =
from feed in categoryProducts.AsEnumerable()[code]....

This all works great.

However, I would like to extend the code to perform some evaluation checks (e.g., check that various columns in the DataTable are not NULL) and other pre-processing (e.g., call various functions to build the image URL based on the image ID - which is another column in the DataTable not shown in the code fragment) before I return the resulting rows of the DataTable as an anonymous type to the client-side.Basically, I want to iterate through the DataTable, perform the evaluation checks and pre-processing, while building my anonymous type manually as I go. Or maybe there is a better way to achieve this?

View 2 Replies

Possible To Assign A Data Type To An Anonymous Type's Members In A Linq Query?

May 5, 2010

If I have a linq query that creates the anonymous type below:

select new
{
lf.id,
lf.name
lf.desc,
plf.childId
};

Is it possible to assign a specific type to one of the members? Specifically I would like to make lf.id a null-able int rather than an int...

View 2 Replies

.net - Get Properties From Anonymous Type In VB.NET?

Feb 12, 2010

I am trying to figure out how to get at an anonymous typed object's properties, when that anonymous type isn't created in the current function.

Specifically, I am binding an ASP.NET ListView to LINQ resultset, then trying to process each item in the ItemDataBound event.

Option Explicit On
Option Strict On
Class MyPageClass
Private Sub Bind()
Dim items As ItemData = FetchItemData()
Dim groups = From s In items Group s By Key = s.GroupId Into Group _
Select GroupID = Key, GroupData = Group
' This works fine:
Dim groupId As Integer = groups(0).GroupID
lvGroups.DataSource = groups
lvGroups.DataBind()
End Sub
Private Sub lvGroups_ItemDataBound(ByVal sender As Object, ByVal e As ListViewItemEventArgs) Handles lvGroups.ItemDataBound
If e.Item.ItemType = ListViewItemType.DataItem Then
Dim item As ListViewDataItem = DirectCast(e.Item, ListViewDataItem)
Dim groupData = item.DataItem ' This is the anonymous type {GroupId, GroupData}
' Next Line Doesn't Work
' Error: Option Strict disallows late binding
Dim groupId As Integer = groupData.GroupId
End If
End Sub
End Class

What do I need to do in lvGroups_ItemDataBound() to get at the item.DataItem.GroupId?

View 2 Replies

C# - Databind Using An Anonymous Type?

Feb 16, 2011

Basically, I have a repeater control, and a Linq query that retrieves some items. Ordinarily I would databind straight to the query and use Eval to populate the template with the results.

However, it doesn't come through in quite the right format - for example, if EndDate is null (it's a DateTime?) then I want to substitute it with "Present". I am using only a couple of the properties in the query result objects.

I am wondering if there's a solution like:

[pseudo madeup code]
var query = getResults();
List<anonymous> anonList = new List();
foreach (var q in query)
{
string myEndDate = "";
if (q.EndDate.HasValue)
{ myEndDate = q.EndDate.ToString(); }
else
{ myEndDate = "Present"; }
anonList.items.add(new { name=q.name, enddate=myEndDate };
}
repeater.Datasource = anonList;

then

<div><%#Eval("enddate")%></div>

View 3 Replies

ADO.NET :: Get Property Of Anonymous Type?

Jan 31, 2011

I use LinqToSql in my project. I have a class called MessageBLL and this class has a method called GetAll which returns List<object>. I returned object because I get data from two tables. Here is my code;

[Code]....

I want to use this in my Default.aspx.cs as like this but intellisense is not show CategoryName :[Code]....suggest me return as IQueryable but I couldn't do it in that way.

View 6 Replies

How To Return Anonymous Type While Using Linq

Jun 30, 2010

Do any one know how to return an anonymous type. I am using Linq where i need to return the following code

private <What's the return type to be provided here> SampleLinq(Int32 Num)
{
var query = (from dept in obj.DeptTable where dept.Id == Num select new { dept.DeptName, dept.DeptId });
return (query)
}

View 8 Replies

Return Anonymous Type From LINQ Query In VB.NET

Mar 25, 2011

I am consuming an RSS feed to display on my website using a repeater control. I was wondering if it's possible in VB to return an anonymous type from my linq query rather than a collection of strongly typed RSSItems. I know this is possible in C#, however haven't been able to work out a VB equivalent.

[Code]....

View 1 Replies

C# - Fill DetailsView.DataSource With Anonymous Type?

Jan 23, 2010

I have an asp:DetailsView with several columns, e.g. Foo, Bar.

I want to fill it with an anonymous type, i.e.:

gridView.DataSource = new { Foo = 1, Bar = "2" };
gridVeew.DataBind();

But getting next error:

Data source is an invalid type. It
must be either an IListSource,
IEnumerable, or IDataSource.

How can I do what I want?

View 3 Replies

DataSource Controls :: Retrieving Properties Of Anonymous Type?

Apr 12, 2010

Usual situation: DataList and LinqDataSource with anonymous types...

Is there any way besides reflection to retrieve properties of anonymous typed DataItem in DataList_ItemDataBound event?

View 2 Replies

Forms Data Controls :: Nested Repeater - How To Get Particular Field Of The Anonymous Type?

Jan 26, 2011

nested repeater like this:

<asp:Repeater ID="repeaterReportListByJob" runat="server" DataSource='<%# GetReportsByJobNID(Eval(Container.DataItem, "JobNID")) %>'>

It seems my Eval(Container.DataItem, "JobNID") is not working and I assume this is because the datasource of the outer (parent) repeater is an anonymous type. So how am I supposed to access a particular field of my anonymous type?

View 7 Replies

Console Application Calling Datalayer Throws An Exception "The Type Initializer For Threw An Exception."

Aug 17, 2010

I have simple 3 tier web application and have mostly CRUDE functionalities. Recently I required to add new console application to the existing solution in which I call data layer methods for retrieving data from DB but I get an exception "The type initializer for threw an exception."When I debugged I found that the exception is thrown at datalayer on first line of class where I get connectionstring from

web.config, the code is public static readonly string CONNECT_STRING =

ConfigurationManager.ConnectionStrings["DbConnectString"].ConnectionString;

Now if I hardcode the connection string value like public static readonly string CONNECT_STRING = "Data Source=XYZ;uid=sa;password=XXX;initial catalog=ABC;"

it works fine.I don't understand what is the issue here as web application works fine with this datalayer.

View 2 Replies

MVC :: How To Display Error In View When There's An Exception While Rendering A Partial View

Feb 16, 2011

I need to display an error message in the view when there's an error in rendering the partial view in that View.

How can i handle the exception while rendering partial view and display the error message in the view?

View 3 Replies

C# - How To Get Untyped Object's Values

Mar 29, 2011

I want to get an object typed properties values. Here is my code:

Type tip = Type.GetType(pair.Key.GetType().ToString());

object uretilenNesne = Activator.CreateInstance(tip);

uretilenNesne has correct type but I want to access uretilenNesne's properties values.

View 1 Replies

C# - Web Service Return Type Exception?

Jul 26, 2010

I have a web service and its methods return a class which is name WSResult. WSResult has 2 properties. One of property's type is int and the other one's type is object. I want to return some different type with this second property.

[code]....

How can i pass an object which i retrieved from other web services or that i generated from my serializable classes inside M_ResultObject property ?

View 2 Replies

MVC :: Change Page Content Type At Runtime?

Oct 25, 2010

I am working in asp.net MVC & on the view has to show both json & xml content depending on some condition.

I have to change the content type of the page at runtime ie,

if the condition for json is fulfilled then set page contenttype = "text/json"

&

if the condition for xml is fulfilled then set page contenttype = "text/xml".

I have tried setting default content type on view as

<%
@
Page
Language="C#"
Inherits="System.Web.Mvc.ViewPage"
ContentType="text/json"%>

& in controller class if xml condition is fulfilled then chnage it like :

this.Response.Clear;

this.Response.ContentType = "text/xml";

BUT it didn't work for me .

View 2 Replies

Configuration :: Exception Of Type 'System.OutOfMemoryException'?

Aug 3, 2010

We have an asp.net 2.0 application in which we get the exception of type 'System.OutOfMemoryException' whenever value is retrieved or stored in viewstate. It does not happen when we test it in local PC but when it is deployed on application server, the exception is thrown.

View 2 Replies

Web Forms :: Exception Of Type 'System.OutOfMemoryException' Was Thrown?

Feb 8, 2010

I have one issue , on that page i have Gridview ie: binding data(by making relationship b/w two tables ) ie: each row contains 75 EasyListbox control so it will be visible as per the condition ie: getting from Database.

But when the page_Loads on that page - First rows shows correctly ie: when i click on paging for Second page - it shows error like this

[code]....

View 13 Replies

Cannot Implicitly Convert Type 'System.Exception' To 'string'

Aug 11, 2010

I want to log all errors happened in my App to sql db. I'm passing all exception properties like (ex.Message, ex.Source, ex.StackTrace, ex.TargetSite and ex.InnerException) to stored procedure.

The problem is that when I try to pass the ex.InnerException as string to stored procedure I got this error:

Cannot implicitly convert type 'System.Exception' to 'string'

I tried ex.InnerException.ToString() and Convert.ToString (ex.InnerException) but no success.

View 4 Replies

Configuration :: Exception Of Type 'System.OutOfMemoryException' Was Thrown?

Jan 20, 2011

I am getting Error Msg Given Below..After Uploading My WebApplication..whenever i try to access my webapplication? what is the exactly reason of this Error. Some time it solved automatically when i try some time later.

Server Error in '/' Application.

Exception of type 'System.OutOfMemoryException' was thrown.
Description:
An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.

View 1 Replies

Getting Error / Exception Of Type 'System.OutOfMemoryException' Was Thrown

Apr 8, 2010

I have an ashx handler with the following code. The idea is to hide the path of the file and prompt a download

[code]....

This works fine for some files however on others i get

Exception of type 'System.OutOfMemoryException' was thrown.

View 2 Replies

MVC :: Type Load Exception When Starting Debugging On New Compile?

Nov 21, 2010

I recently downloaded the mvc 3 RC and I am receiving a type load exception everytime i do a fresh compile and start a debugging session. The error is

System.TypeLoadException crossed a native/managed boundary

[code]...

I can click ok and my debug session continues working as normal. I can close the session and restart without making any code changes, and it will open and work correctly. But, everytime I close, make a compilable change and rerun, I get the message.

View 15 Replies

C# - ELMAH - Only Sending Specific Exception Type Via Mail

May 31, 2010

I have ELMAH set up for a webapp, logging exceptions to a SQL server. I wish to have ELMAH send me an email too, but only when a specific exception is thrown (ie. MySpecialException). ELMAH must still log all exceptions to SQL server. I know you can do it programmatically in global.asax, but I'd prefer to use web.config. So, how do I restrict ELMAH error mails to filter out everything but a specific exception type, using web.config? UPDATE The filter ended up looking like this:

<test>
<and>
<not>
<is-type binding="Exception" type="MyApp.MySpecialException" />
</not>
<regex binding="FilterSourceType.Name" pattern="mail" caseSensitive="false"/>
</and>
</test>

View 1 Replies

WCF / ASMX :: Exception Of Type 'System.OutOfMemoryException' Was Thrown

Nov 30, 2010

I am getting this exception whenever i tried to delete the WCF Service reference in project.I cannot even update it.Our WCF Service is bit huge and looks like this is causing the issue.I Start/Stopped IIS web server but still i cant get rid of it.

View 1 Replies







Copyrights 2005-15 www.BigResource.com, All rights reserved