Hi All,
I'm designing a user control, briefly it contains an asp:hiddenfield control, i'm going to access it via JavaScript function like this
function doAnyThing
{
var myVar = document.getElementById("myHiddenFiled");
}
but when I trace my code I found myVar assigned to null, does it matter
document.getElementById()
method is used in user control file (.ascx) or in regular (.aspx) file, taking into consideration it works in (.aspx) file correctly
You had to set by ClientID the final id of your control, that will depend by the structure of your page.
Try this:
function doAnyThing
{
var myVar = document.getElementById("<%= yourControlServerID.ClientID %>");
}
Obviously this function need to be placed in the .aspx file. I suggest you to switch to use a framework like jQuery, that allows you to retrieve controls by more sofisticate selectors. This case will be solved by:
$("[id$=yourControlServerID]");
and you can place your javascript code even in an external .js file.
to simplify you can use either:
JQuery
$("<%= yourControlServerID.ClientID %>"). ....
ASP.NET JavaScript annotation:
var myVar = $get("<%= yourControlServerID.ClientID %>");
the ASP.NET JavaScript annotation code is the same as:
var myVar = document.getElementById("<%= yourControlServerID.ClientID %>")
Related
In asp.net I took one master page and one Web Form selected with the master page.
In first web form i have one textbox and button.
When button click then OnClientClick property contains validate() function
Now In master page's coding I written as following :
function validate() {
var no = document.getElementById('<%=Page.Master.FindControl("ContentPlaceHolder1").FindControl("TextBox1").ClientID %>').value;
if (isNaN(no)) {
alert('not a number.');
}
}
Now i took second web form
In that i put one calendar control and just run it
error occurs as following :
Object reference not set to an instance of an object.
Line 11: function validate() {
Line 12: var no = document.getElementById('<%=Page.Master.FindControl("ContentPlaceHolder1").FindControl("TextBox1").ClientID %>').value;
Line 13: if (isNaN(no)) {
Line 14: alert('not a number.');
I am seeing Line 12 : as a red line.
So How to run this second Web Form
Inside content page declare an in-line Javascript variable.
<script>
var jsTextBox1Id = <%=TextBox1.ClientID%>;
</script>
Now you can access the control ID in Validate() using global jsTextBox1Id variable.
Like this:
var no = document.getElementById(jsTextBox1Id).value;
(Remember this type of approach is not a recommended practice.)
Update
To get a reference to the HTML element that is rendered for any control in client script, you must know the value of the control's ClientID property. However, because the user control can be put anywhere in a Web page, it is impossible to know in advance which naming containers will contain the controls. To make sure that the ClientID value will be the same as the ID value, the just set the ClientIDMode value to Static.
<asp:TextBox ID="MyStaticId" runat="server" ClientIDMode="Static">
</asp:TextBox>
Now you can access it using the ID defined by you MyStaticId, it will not have prepended parent container name to it.
document.getElementById("MyStaticId").value
Source MSDN
I have web application where i want to call one method on body onload method.
I have method like this
<body id="pageid1" onload="SetupFeaturedProperty(1,['http://www.brightlogic-estateagents.co.uk/MRUS/upload/918-1.jpg', 'http://www.brightlogic-estateagents.co.uk/MRUS/upload/918-2.jpg', 'http://www.brightlogic-estateagents.co.uk/MRUS/upload/918-3.jpg', 'http://www.brightlogic-estateagents.co.uk/MRUS/upload/918-4.jpg']);SetupFeaturedProperty(2,['http://www.brightlogic-estateagents.co.uk/MRUS/upload/665-1.jpg', 'http://www.brightlogic-estateagents.co.uk/MRUS/upload/665-2.jpg', 'http://www.brightlogic-estateagents.co.uk/MRUS/upload/665-3.jpg', 'http://www.brightlogic-estateagents.co.uk/MRUS/upload/665-4.jpg']);SetupFeaturedProperty(3,['http://www.brightlogic-estateagents.co.uk/MRUS/upload/38-1.jpg', 'http://www.brightlogic-estateagents.co.uk/MRUS/upload/38-2.jpg', 'http://www.brightlogic-estateagents.co.uk/MRUS/upload/38-3.jpg', 'http://www.brightlogic-estateagents.co.uk/MRUS/upload/38-4.jpg']);SetupFeaturedProperty(4,['http://www.brightlogic-estateagents.co.uk/MRUS/upload/122-1.jpg', 'http://www.brightlogic-estateagents.co.uk/MRUS/upload/122-2.jpg', 'http://www.brightlogic-estateagents.co.uk/MRUS/upload/122-3.jpg', 'http://www.brightlogic-estateagents.co.uk/MRUS/upload/122-4.jpg']);SetupFeaturedProperty(5,['http://www.brightlogic-estateagents.co.uk/MRUS/upload/1076-1.jpg', 'http://www.brightlogic-estateagents.co.uk/MRUS/upload/1076-2.jpg', 'http://www.brightlogic-estateagents.co.uk/MRUS/upload/1076-3.jpg', 'http://www.brightlogic-estateagents.co.uk/MRUS/upload/1076-4.jpg']);">
And the arguments of these method can be change in after some time.
I want to pass the argument when my page is loaded.
I have tried lot of method to pass the argument from code behind page to this page but it's not working.
Please let me know a better solution for this.
Thanks
use this:
Page.ClientScript.RegisterStartupScript(this.GetType(), "myScript",getScript(),true);
and then:
private string getScript()
{
return "SetupFeaturedProperty(etc,etc,etc);";
}
If you are using UpdatePanels use the ScriptManager class instead of Page.ClientScript
There are multiple ways to do this. You can register the scripts using the RegisterClientScript method. You can make the body tag a server control and set it's onload attribute in the code behind or you can use Literal tag. However the method I find most clean is creating a JS variable and assigning it's value with a serverside code then using this variable in your JS code:
<script> var someVariable = <%= SomeProperty %>;</script>
Make sure that you define properties in your page and not move all your code behind in the markup.
Another good approach is to define a function for your event that takes the element as an input (pass this as the argument) and then attach the actual arguments as different attributes to the element.
<body runat="server" id="body" onload="onLoad(this)" data-someArg="someValue">...
You can set the attributes from your code behind like this
body.Attributes["data-someArg"] = "someValue";
This will be invalid in HTML4 but will work fine in all browsers and it will be valid in HTML5 as long as you prefix the attribute name with data-
Use ClientScript.RegisterStartupScript. Check MSDN:
MSDN - Javascript and ASP.NET 2.0
MSDN - ClientScript.RegisterStartupScript
One way to do it is to setup a Literal tag in your javascript. For example:
function somemethod()
{
var number1 = 10;
var number2 = <asp:Literal ID="litNumberFromCode" runat="server"/>;
alert(number1 + number2);
}
Then in your code behind access that control like any other:
litNumberFromCode.Text = 15;
Try using inline c# <% %> with your values printing
I am struggling with something that I guess should be standard practice really. I have a number of user controls that use some JQuery plugins. I do not really want to link to the extra CSS and JS files from my main masterpage as this would cause extra load to the user the first time they hit the site, (admittedly it would only be the once), so I was just putting them links into the top of the user control. Then I looked at my source HTML, not nice! Even worse for controls that repeat multiple times on a page.
So I was thinking is there a way of injecting them into the Head of the page when they are needed from the User Control. For that matter is there a way of doing it to the footer for JS stuff?
To dynamically register a script (and ensure that duplicates are merged) in ASP.NET you can call:
Page.ClientScript.RegisterClientScriptInclude(
"mykey", "~/scripts/jquery-1.3.2.js");
And read the full details on this method on MSDN.
To add CSS dynamically you can do something like this:
HtmlLink cssLink = new HtmlLink();
cssLink.Href = "path to CSS";
cssLink.Attributes["some attr1"] = "some value1";
cssLink.Attributes["some attr2"] = "some value2";
Page.Header.Controls.Add(cssLink);
This example of injecting CSS will not merge duplicate entries. To avoid duplication you'll have to keep track of duplicates yourself. One place you can store a list of scripts you've already registered is in HttpContext.Items. Stick a HashSet in there that keeps a list of all registered scripts so that you don't register the same CSS file twice (which is generally harmless, but something to avoid anyway).
I followed a similar approach, but I use CSS directly in the user control so I don't have to import a CSS file. The following is code entirely from a sample user control:
<style id="style1" type="text/css" visible="false" runat="server">
td { font-family: Tahoma; font-size: 8pt; }
</style>
In code-behind:
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
HtmlGenericControl style = new HtmlGenericControl("style");
style.Attributes.Add("type", "text/css");
style.InnerHtml = style1.InnerHtml;
Page.Header.Controls.Add(style);
}
You'll notice that the CSS is rendered in the head tag and not inside the body tag.
You can use ClientScript.RegisterClientScriptInclude() for the JavaScript.
For the CSS, one trick is to include them in your Master page, but with Visible="false", so that they aren't rendered into the markup by default.
Then, in your user controls, set a flag in the Items collection, from an early event, such as OnLoad(). For example, this.Context.Items["mycss"] = true;
Finally, in your Master page, from a later event, such as OnPreRender(), check to see if those flags are set. If they are, then set the Visible property to true for the corresponding CSS.
This also allows you to use the control with Master pages that don't use the CSS, since the Items entries could simply be ignored. If you have many Master pages that need the same behavior, you could put this code in a base class or use nested Master pages.
I assume you're using Asp.NET.
Try putting a content placeholder in the of the MasterPage...
<head>
<asp:ContentPlaceHolder ID="AdditionalPageHeader" />
</head>
If you're working in an aspx file or an ascx you need only define a content control...
<asp:Content ContentPlaceHolderID="AdditionalPageHeader" />
If you're working on a code-behind only type of server control, you can can get a pointer to that content place holder:
this.Page.Master.FindControl("AdditionalPageHeader")
... and manipulate it's contents programatically.
To add stylesheets or javascript (inline or not) dynamical I wrote these three functions:
Public Function addScript(ByVal path2js As String) As System.Web.UI.Control
Dim si As New HtmlGenericControl
si.TagName = "script"
si.Attributes.Add("type", "text/javascript")
si.Attributes.Add("src", path2js)
Return si
End Function
Public Function addScript_inline(ByVal js As String) As System.Web.UI.Control
Dim si As New HtmlGenericControl
si.TagName = "script"
si.Attributes.Add("type", "text/javascript")
si.InnerHtml = js
Return si
End Function
Public Function addStyle(ByVal path2css As String) As System.Web.UI.Control
Dim css As New HtmlLink
css.Href = path2css
css.Attributes.Add("rel", "stylesheet")
css.Attributes.Add("type", "text/css")
css.Attributes.Add("media", "all")
Return css
End Function
I call them in page_load on my masterpage, like this:
Me.Page.Header.Controls.Add(modGlobal.addScript("script/json/json2.js"))
or
Me.Page.Header.Controls.Add(modGlobal.addStyle("style/flexigrid/flexigrid.css"))
Regards
I am creating a custom .NET AJAX Server Control, and need to get access to the JavaScript object functionality associated with that control. I can do this by finding the control in the ScriptManager using the $find method. However, I need to determine when I can call $find. If I do this on the "onload" event of the body of my HTML page, it can't find the control. Thus I end up having to locate the control with each event I wire up and my code ends up looking like this:
function button1_click() {
var control = $find("<%=Control.ClientID%>");
control.DoSomething();
}
function button2_click() {
var control = $find("<%=Control.ClientID%>");
control.DoSomethingElse();
}
I would rather store that control once, and use it throughout the rest of my event calls. Thus I'm hoping the code would eventually look something like this:
var _control = null;
function load() {
_control = $find("<%=Control.ClientID%>");
}
function button1_click() {
_control.DoSomething();
}
function button2_click() {
_control.DoSomethingElse();
}
Let me know if this doesn't make sense. I am new at creating these custom controls, so I'm not quite sure of the terminology yet. Thanks for your help!
The "load" DOM event occurs before the ASP.NET Ajax client-side framework is initialized. Client-side controls are initialized by handling the init event of the Sys.Application object. That's why an ASP.NET Ajax control's initialization script is output like:
Sys.Application.add_init(function() {
$create( ... )
});
You can use the load event of the Sys.Application object or its shortcut- the pageLoad method. It occurs after the init event and all ASP.NET Ajax controls will be initialized then. Here is some sample code:
var _control = null;
function pageLoad() {
_control = $find("<%= Control1.ClientID %>");
}
I am very new to jQuery and have got a quick question.
I wish to use my server side classes in my jQuery code, something similar to this:
$(document).ready(function() {
var temp = <%# myClass.Id %>;
})
Is this possible? if so, how?
Thank you very much
This is the later question I refined my former question to:
I'm sorry, I think I didn't explain myself too well... I've got a class name User. It's a class I built in my business logic.
I've got a web page named UserProfile, inside it I've got the following property exposing the current logged in user:
public BL.User CurrUser { get { return (BL.User)Session["currUser"]; } }I want to be able to access this User class from my aspx page using Jquery. How do I do that?
The databinding syntax
<%# MyStaticClass.MyProperty %>
will only work if you call DataBind on the container (page). What you're after is most likely the following syntax:
<%= MyStaticClass.MyProperty %>
which will also give you access to you page / control members
<%= this.MyPageProperty %>
As was already mentioned you should really assign those values to java script variables and pass those variables to you JS functions.
This will only work if your javascript is embedded in your source files (e.g. the .aspx files):
<script type="text/javascript">
var id = <%# myClass.Id %>; // store as raw value
var id_string = '<%# myClass.Id %>'; // store in a string
</script>
As others have said, if the JavaScript is in your aspx page, then using server tags will work fine.
If you have your jQuery in an external script file, then you could put this in your aspx page
<script type="text/javascript">
var myClass = $('#<%= myClass.ClientID %>');
</script>
and then use the variable in your external script file
$(function() {
myClass.click( function() { ... });
});
For other options take a look at this question and answer - How to stop ASP.NET from changing ids in order to use jQuery