Issue getting .ClientID in ASP.NET C#

Ben Drury picture Ben Drury · Aug 22, 2011 · Viewed 49.3k times · Source

I have the following in the uploadError javascript function for AsyncFileUpload from AJAX toolkit:

function uploadError(sender, args) {
    document.getElementById("<%# uploadResult.ClientID %>").innerText = args.get_fileName(), "<span style='color:red;'>" + args.get_errorMessage() + "</span>";
}

Unfortunately the ClientID call returns Null, so the javascript errors.

I have also noticed that none of my controls have the usual .NET format once the page is loaded: E.G.:

<asp:Label runat="server" Text="Select an image to upload it to this stock item...." ID="uploadResult" /> 

Would usually render like this:

<span id="ctl00_ContentPlaceHolder1_uploadResult">Choose a webstock file to upload...</span>

But with this file it is rendering as:

<span id="uploadResult">Select an image to upload it to this stock item....</span>

I presume this is the same issue, but don't know why it's happening.

Answer

Kelsey picture Kelsey · Aug 22, 2011

The problem is you are using the <%# syntax which is only executed on binding (evals).

You should be using <%= syntax which will always execute.

Eg:

function uploadError(sender, args)
{
    document.getElementById('<%= uploadResult.ClientID %>').innerText = 
        args.get_fileName() + "<span style='color:red;'>" + 
        args.get_errorMessage() + "</span>";
}

Reference for more information on asp.net inline syntax.

Data-binding Syntax

Inline Syntax

EDIT: Note you had , in your assignment to innerText which would also be an issue if it is not a typo.