This might be a really dumb question but I\'m learning .NET, so I\'m quite clueless...
Let\'s say I have two files default.aspx and the associated default.a
You can declare variable as protected in code behind (.cs) and then call that on aspx page to retrieve all data.
e.g.
protected IEnumerable<Class> _mydata;
internal void MyDefaultData()
{
mydata = doallthework;
}
on aspx page you can do like following
<%=_mydata.FirstOrDefault().FirstName%>
Make sure method is called on load.
You can, but you'll have to do it a bit differently. In your default.aspx.cs, add a member:
protected MyObject _myObject;
Then, in Page_Load:
protected void Page_Load(object sender, EventArgs e)
{
_myObject = new MyObject();
}
Then, in default.aspx, you can do:
<%= _myObject.SomePropertyOfThisObject %>
Of course, this assumes that class MyObject has a property named Awesome. You didn't mean the System.Object class, did you, since it doesn't have a property named Awesome.
Since your question was asking about the best way, I'll go further. The way I showed is not the best. The best is more often to use a data binding expression. If you don't like those, then you can set things in the codebehind:
protected void Page_Load(object sender, EventArgs e)
{
_myObject = new MyObject();
//
_myLabel.Text = _myObject.SomePropertyOfThisObject;
}
Assuming:
<asp:Label runat="server" id="_myLabel" />
The <%= ... %> is ASPX short-hand for Response.Write( .... )
.
If you change myObject to be strongly types (rather than just types as Object) you can certain use the line:
<%= myObject.Awesome %>
to emit a value.
Be aware, however, that the <%= syntax has limitations - specifically:
You are probably better off creating a Label control on you page, and programmatically setting the Text
property to the value. This also gives you more control over how value-to-string conversions are performed. And will work correctly with update panel controls.
You can do any coding that you'd like to do directly in the ASPX file, rather than using codebehind. So, to accomplish what I think you want to do, you would have...
<some html>
<% var MyObject = new MyObject();
Response.Write(myObj.Awesome()); %>
<some html>
However, this is really not recommended. Codebehind is the suggested "best practice" way of doing things, because this separates your code from your markup, which is fundamental in any good architecture. I would recommend using something like what John Saunders posted in order to avoid databinding, but you should really consider manipulating your controls in the codebehind using the lifecycle events rather than outputting object properties directly to your HTML. For example, if you were trying to output some text, then do something like
var literal = new LiteralControl(myObject.Awesome());
myPanel.Controls.Add(literal);
Doesn't it have to be public to be accessible in that scope?
..
public var myObject = null;
protected void Page_Load(object sender, EventArgs e)
{
myObject = new Object();
}