Szabolcs Antal
Szabolcs Antal

Reputation: 957

Get variable in javascript from aspx.cs

I have an aspx form called MyForm.aspx. In this form I had included a javascript file:

<script type="text/javascript" src="Scripts/MyForm.js"></script>

In MyForm.aspx.cs a have a property:

public string Username { get; set; }

How can I access this Username variable in the MyForm.js?

I tried in the following way but its not working: var username = '<%=this.Username%>'

Upvotes: 0

Views: 2973

Answers (2)

sanepete
sanepete

Reputation: 1130

Call the javascript from a server side generic handler file:

<script type="text/javascript" src="cogs/awesomejavascript.ashx"></script>

Output all of the javascript from the handler file:

public void ProcessRequest (HttpContext ctx)
{
        ctx.Response.ContentType = "text/plain";
        StringBuilder bild = New StringBuilder;
        bild.Append("var username = " + this.username);
        ctx.Response.Write(bild.ToString);

}

If you're not comfortable with handler files you could use an ascx file.

Upvotes: 1

Rumen Jekov
Rumen Jekov

Reputation: 1675

The JavaScript engine will be unable to resolve the server <%=this.Username%> code in a JS file since the server tags are not part of its specification. These server brackets can be resolved only inside the aspx/ascx files by the ASP.NET engine.

You can create a function in the MyForm.js file that accepts as an argument the ID of the username field getUserName(userName){ return userName;} and call the function from the MyForm.aspx page like this:

[MyForm.aspx]

var username = '<%=this.Username%>';
getUserName(userName);

[MyForm.js]

getUserName(userName)
{
   return userName;
}

Upvotes: 0

Related Questions