从 ASP.NET 中的标记访问我的类背后代码的属性的最佳方法 [英] Best way to access properties of my code behind class from the markup in ASP.NET

查看:19
本文介绍了从 ASP.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%>

... 或类似的东西,而不必使用数据绑定器或像这样复杂的东西?如果无法绑定数据,那么最好的方法是什么?

... 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 有一个名为 Awesome 的属性.您不是指 System.Object 类,是吗,因为它没有名为 Awesome 的属性.

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

假设:

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

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

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