Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
212 views
in Technique[技术] by (71.8m points)

c# - Best way to access properties of my code behind class from the markup in ASP.NET

Let's say I have two files default.aspx and the associated default.aspx.cs.

default.aspx.cs:

protected void Page_Load(object sender, EventArgs e)
{
    var myObject = new MyObject();
}

Is there a way that in the default.aspx I could do something like:

<%= myObject.SomePropertyOfThisObject%>

... or something similar, without having to use databinders or something complicated like this? And if there's no way around binding the data, what would be the best way to do it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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" />

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...