<%# Eval(“State”) %> or <%#

2019-03-09 20:18发布

问题:

What is the difference between having

<%# Eval("State") %>

in your aspx page, versus having

<%# DataBinder.Eval(Container.DataItem, "State") %>

in your aspx page?

回答1:

Eval("State") is a simplified form of the DataBinder.Eval(Container.DataItem, "State") syntax. It only works inside of data-bound template controls.

For more info, see the MSDN documentation.



回答2:

There is no difference. The "Eval" method is just a shortcut for the DataBinder.Eval(Container.DataItem, "blah") method.



回答3:

There are a lot of differences between <%# Eval %> and <%# DataBinder.Eval %> under the covers, even though the documentation states that using Eval (TemplateControl.Eval to be exact) actually calls DataBinder.Eval and that their task is to do exactly the same job.

That is correct, but using just Eval means that ASP.NET itself resolves the object that is databound. It does this internally with a stack where items are added when Control.DataBind() is called. The trick is that this happens only if the Page property of the control is non-null at that point.

If the Page-managed stack isn't up to date when you get to the point that DataItem needs to be resolved, the Page.GetDataItem() method will give an exception with a message like

Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control.

DataBinder.Eval still works in those circumstances because you provide it the target object manually, so ASP.NET doesn't need to do any resolving on its own.



回答4:

the Eval method is just a shortcut of the latter



回答5:

I have seen following code

<%# (DataBinder.Eval(Container.DataItem, "ApplicationId").ToString() == "-1" ? "N/A" : Eval("ApplicationId").ToString()) %>

So I guess they slightly different.