The below code works but I am not sure how?
OnClientClick='<%# CreateConfirmation(Eval("EventName"),DataBinder.Eval(Container.DataItem, "EventDate", "{0:ddd, d MMM}")) %>'
Public Function CreateConfirmation(ByVal EventName As String, ByVal EventDate As String) As String
Return String.Format("return confirm('Are you sure you wish to register for {0} on {1} ?');", EventName, EventDate)
End Function
I have read that <%# %> is a databinding expression, but overhere we are not directly data-bidning (infact returining value from the function CreateConfirmation) and I also thought that it should work with <%= %> but it gives JavaScript error message i.e. Illigal XML character
pointing to =
Please could you clarify as to why is this?
Many Thanks.
This question is very precisely answered in an exisiting post:
Why will <%= %> expressions as property values on a server-controls lead to a compile errors?
You can call any code inside the <%#. The Eval bit is the piece that makes it relate to the row/object in the datasource.
You are still binding the returned string to the property. You can only use <%=%> with inline HTML. You have to use <%#%> when binding to a contols property.
Related
Apparently it is possible to write formatted output using the <%= %> construct (render block) in ASP.NET web forms pages and views.
<%= "{0} is {1}", "Foo", 42 %>
This will render "Foo is 42". As far as I know the ASP.NET parser translates <%= %> into a call to HttpResponse.Write(string). Obviously in the code above, there is no one-to-one translation, because the number of arguments don't match (assuming the , in the expression above separates arguments).
Now I have seen that the class TextWriter has a Write(string, object[]) method.
I have checked the output from the parser, and indeed it calls the TextWriter's method that accepts a params object[] argument for formatting:
private void #__Renderform1(System.Web.UI.HtmlTextWriter #__w, System.Web.UI.Control parameterContainer) {
// ...
#__w.Write( "{0} is {1}", "Foo", 42 );
Is that behavior documented anywhere?
As far as I know the ASP.NET parser translates <%= %> into a call to
HttpResponse.Write(string).
Maybe the <%= "{0} is {1}", "Foo", 42 %> is translated to Response.Output.Write(string format, params object[] arg), Output being of type TextWriter, which would be the explanation
according to http://www.hanselman.com/blog/ASPNETResponseWriteAndResponseOutputWriteKnowTheDifference.aspx
This is an <%= %> embedded code block and exists to maintain compatibility with Classic ASP.
As you saw <%= "{0} is {1}", "Foo", 42 %> is equivalent to:
string s = string.Format("{0} is {1}", "Foo", 42);
Response.Write(s);
That behavior is documented here:
Writes a formatted string that contains the text representation of an object array
to the output stream, along with any pending tab spacing.
This method uses the same semantics as the String.Format method.
(Overrides TextWriter.Write(String, Object[]).)
Here is where it's documented that the Code Render Block calls the Write method.
Finally, the syntax for embedded code blocks has been updated for .NET 4 as described here.
This is close and perhaps related http://msdn.microsoft.com/en-us/library/586y06yf.aspx but it's not an explanation for why the <%= does it...
I saw a piece of ASP code that looks as follows:
<% rs("Server.HTMLEncode(x)") %>
Since I doubt that the recordset has a field named "Server.HTMLEncode(x)" I was wondering if they meant to write:
<% Server.HTMLEncode(rs(x)) %>
Or if classic ASP does reflection and somehow interprets that string literal as a method call.
I used classic ASP for ten years, and I never encountered any kind of reflection. Based on my past experience, I would agree with you that they probably meant to write:
<% Server.HTMLEncode(rs(x)) %>
But, it still does not look correct. Did they mean to write out the value using Response.Write? I can't tell without seeing more of the code.
Looks like bad coding to me.
Classic ASP can be written with VBScript which does allow kind of reflection by using Eval() and Execute() methods. For example:
Class Foo
Public Bar
End Class
Dim oFoo, propName, myValue
Set oFoo = New Foo
oFoo.Bar = "hello world"
propName = "Bar"
myValue = Eval("oFoo." & propName)
Response.Write("Value of " & propName & ":" & myValue)
However, that's not the case with your sample code. This is just a string literal passed to the Recordset object which looks for exact match. If the given parameter is a number it will return value of field having such index otherwise it expects a string which is exact field name.
Assuming x is user input that should be a field name or index, they probably meant:
<%=rs(Server.HTMLEncode(x)) %>
i have a line of code that is throwing a Specified cast is not valid exception:
<%# DecimalToStringUsingUserLocale( (Decimal)Eval("HoursBooked") ) %>
i want to have a breakpoint on this line, so i can inspect the value of:
Eval("HoursBooked")
to see what type the underlying Object is. How can i do this?
How can i put a breakpoint on a databinding expression line?
Workaround
Move presentation from the view to the controller:
<%# HoursBookedToStr(Eval("HoursBooked")) %>
and then in the code-behind file:
protected string HoursBookedToStr(Object objectFromEval)
{
Decimal value = (Decimal)objectFromEval;
return DecimalToStringUsingUserLocale(value);
}
and now i can put a breakpoint on the line:
Decimal value = (Decimal)objectFromEval;
Note: Now i can solve my problem because i see the object is not of type Decimal, as i thought, but instead is of type System.DBNull
How can i put a breakpoint on a databinding expression line?
Note: Don't confuse the example with the question: placing breakpoints on databinding.
I want to set properties Enabled='<%=Exceeds2dCatalogCount()?false:true%>' to my asp.net button. but It gives me an error
Cannot create an object of type 'System.Boolean' from its string
representation '<%=Exceeds2dCatalogCount()?false:true%>' for the
'Enabled' property.
Is there any solution for this?
You have to use <%# %> (Binding expression) and invoke DataBind() to write value at property. Depends upon the return datatype of your page method Exceeds2dCatalogCount() you may write following code.
Enabled='<%# Exceeds2dCatalogCount() ? false : true %>' //<---If return type is boolean.
Enabled='<%# (Exceeds2dCatalogCount()==1 ? false : true) %>'
Invoke the YourControlID.DataBind() method in page_load event.
I guess I am curious what is better?
Casting the DataItem to the type i know it is...
Or
pass the object to a function that expects a Dynamic, and let the DLR do its magic.
<asp:Repeater ID="rptItems" runat="server">
<ItemTemplate>
<div>
<%# FormatBlogLink(Container.DataItem) %>
OR
<%# FormatBlogLink((BlogPost)Container.DataItem) %>
</div>
</ItemTemplate>
</asp:Repeater>
Code
protected string FormatBlogLink(dynamic blogPost)
{
/// Do a bunch of stuff
}
vs:
protected string FormatBlogLink(BlogPost blogPost)
{
/// Do a bunch of stuff
}
My example is simple,
I thought i read that the DLR will cache things it looked at so it,
so I am curious, what is worst for larger data sources... lots of casting or lots of using dynamic?
(or) am i a bit crazy ... :)
My personal opinion would be to cast to the appropriate type, if that is what you are expecting to use. The only reason to use dynamic in your FormatBlogLink is if you expect to pass different objects that just happen to share the same property names and methods, etc. Otherwise, cast to the appropriate type and benefit from intellisense.
I too would opt for the cast - but you can do this in your FromatBlockLink - method (let it take object). This has the advantage that you remove this (little) logic from your view and of course you can check the type in your function.
protected string FormatBlogLink(object blogPost)
{
var post = blogPost as BlogPost;
if (post == null)
{
// throw or use show error-message
}
/// Do a bunch of stuff
}