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%>'
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.
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.