最好的方法,从ASP.NET中的标记访问隐藏类我的code的性能 [英] Best way to access properties of my code behind class from the markup in ASP.NET

查看:116
本文介绍了最好的方法,从ASP.NET中的标记访问隐藏类我的code的性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个非常愚蠢的问题,但我学习.NET,所以我很无能...

让我们说我有两个文件的Default.aspx和相关default.aspx.cs。

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

default.aspx.cs:

default.aspx.cs:

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

有没有办法,在Default.aspx的,我可以做这样的事情:

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

<%= myObject.SomePropertyOfThisObject%>

...或者类似的东西,而不必使用复杂的这样databinders什么?如果没有办法解决绑定中的数据,这将是做到这一点的最好方法是什么?

... 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?

推荐答案

可以,但你必须以不同的方式做到这一点。在你default.aspx.cs,添加成员:

You can, but you'll have to do it a bit differently. In your default.aspx.cs, add a member:

protected MyObject _myObject;

然后,在Page_Load中:

Then, in Page_Load:

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

然后,在Default.aspx的,你可以这样做:

Then, in default.aspx, you can do:

<%= _myObject.SomePropertyOfThisObject %>

当然,这是假定类为MyObject有一个名为真棒属性。你并不意味着System.Object类,没有你,因为它没有一个属性命名真棒。

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.

由于你的问题问的是的的方式,我会走的更远。我展示的方式是不是最好的。最好是更经常使用的数据绑定前pression。如果你不喜欢这些,那么你可以设置的东西在codebehind:

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;
}

假设:

<asp:Label runat="server" id="_myLabel" />

这篇关于最好的方法,从ASP.NET中的标记访问隐藏类我的code的性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆