[英]Is there a way - in ASP.Net - to access one ObjectDataSource's object from another ObjectDataSource in code behind?
I have following code in aspx page: 我在aspx页面中有以下代码:
<asp:ObjectDataSource id="odsOuterSource" TypeName="my.namespace.page"
SelectMethod="GetTestObject" DataObjectTypeName="my.namespace.Entities.TestObject" />
<asp:ObjectDataSource id="odsInnerSource" TypeName="my.namespace.page"
SelectMethod="GetAnotherTestObject"
DataObjectTypeName="my.namespace.Entities.AnotherTestObject" />
and following code in code-behind: 以及下面代码中的代码:
public TestObject GetTestObject()
{
Logic myLogic = new MyLogic();
return myLogic.GetTestObject();
}
public AnotherTestObject GetAnotherTestObject()
{
Logic myLogic = new MyLogic();
return myLogic.GetAnotherTestObject(testObject);
}
Now my question is if there is a way to get the TestObject which was returned by the OuterSource so that I could use it for the InnerSource without having to call GetTestObject again. 现在我的问题是,是否有一种方法可以获取由OuterSource返回的TestObject,以便我可以将其用于InnerSource,而不必再次调用GetTestObject。
I hope you can help me with this. 希望您能帮到我。
Edit: For better readability than a comment 编辑:比注释更好的可读性
Thanks for your answers, but i have a question to Mudu's answer: 感谢您的回答,但我对Mudu的回答有疑问:
Is there a way to do this if my OuterSource has a parameter? 如果我的OuterSource有参数,有没有办法做到这一点? For example
例如
<asp:ObjectDataSource id="odsOuterSource" TypeName="my.namespace.page"
SelectMethod="GetTestObject" DataObjectTypeName="my.namespace.Entities.TestObject">
<SelectParameters>
<asp:QueryStringParameter Name="id" QueryStringField="id" DefaultValue="0" />
</SelectParameters>
</asp:ObjectDataSource>
because then even my GetTestObject would have a parameter: 因为即使我的GetTestObject也会有一个参数:
public TestObject GetTestObject(int id)
{
Logic myLogic = new MyLogic();
return myLogic.GetTestObject(id);
}
You could save it in a member, either as TestObject
or as a Lazy<TestObject>
: 您可以将其保存为成员,作为
TestObject
或Lazy<TestObject>
:
private readonly Lazy<TestObject> myTestObject = new Lazy<TestObject>(() =>
{
var myLogic = new MyLogic();
return myLogic.GetTestObject();
});
With this code, you can receive it any number of times you want. 使用此代码,您可以任意次数接收它。 It will be fetched via
MyLogic
once and re-returned on subsequent invocations: 它将通过
MyLogic
一次获取,并在随后的调用中返回:
public TestObject GetTestObject()
{
return this.myTestObject.Value;
}
public AnotherTestObject GetAnotherTestObject()
{
var testObject = this.myTestObject.Value; // re-used
Logic myLogic = new MyLogic();
return myLogic.GetAnotherTestObject(testObject);
}
As ASP.NET creates a new instance of your page for each request, the Lazy<TestObject>
object is recreated for each request. 当ASP.NET为每个请求创建页面的新实例时,将为每个请求重新创建
Lazy<TestObject>
对象。 Therefore, your TestObject
is actually fetched once per request. 因此,您的
TestObject
实际上每个请求获取一次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.