Add packaged javascript to page from ASP.NET server control? - asp.net

Is it possible to create an ASP.NET server control that packages some javascript that will be emitted to the aspx page at design-time rather than run time? I am trying to create a control that will have "default" javascript. I can add jvascript using RegisterClientScriptBlock, but then a web developer can't modifiy the javascript - it is unavailable a design-time in this scenario. Is there a way to change the ToolBox properties so that when a web developer drops the control onto the page, the javascript is added in a separate script tag as well?

When I need to do this I make a property on the control that will inject the tags, and then the web dev makes a asp:literal tag that has visibility none and viewstate disabled, that has all the JS they need.
then in the page's code behind they inject the literal's text into the server controls properties.
<asp:Literal ID="Literal_HtmlHeader" runat="server" Visible="false" EnableViewState="false">
<script></script>
<style></style>
</asp:Literal>
there are probably better ways... but this is simple and effective for me.
protected void Page_Load(object sender, EventArgs e)
{
if (!String.IsNullOrEmpty(this.Literal_HtmlHeader.Text.Trim()))
{
//inject css and js into header.
Page.Header.Controls.Add(new LiteralControl(this.Literal_HtmlHeader.Text));
// or add to your control cause it knows how to add the tags so there is no duplication.
ServerControl c = new ServerControl();
c.HtmlHeaderCode = this.Literal_HtmlHeader.Text.Trim();
}
}

Related

Hiding Literal control declaratively in header (ASP.NET web forms)

I try to hide some Javascript code in header by just using declarations. The Visible property should be controlled by a setting in web.config (ConfigurationManager.AppSettings["key"]).
However, for some reason setting the Visible property like this has no effect - it is always true:
<head id="Head1" runat="server">
<asp:Literal ID="JSLiteral" runat="server" Mode="PassThrough" Visible='<%# false %>'>
Some JS
</asp:Literal>
</head>
It is probably linked to page life cycle in ASP.NET. It works when setting this property in Page_Load event, but that's not what I want as I need to insert this block to a lot of web applications, and I don't want to recompile all of them.
Any ideas how this could be accomplished with minimal effort in ASP.NET? I don't want to mess around with the JS code, which needs to be added in header - it is code of a third-party.
Thanks in advance and cheers,
Roger
Try the following.
protected void Page_Load(object sender, EventArgs e)
{
Head1.DataBind();
}
What you are using is a DataBinding expression. So DataBind() has to be called.

Acess a control of a user control in a content page of a master page

I have user control (ascx) in a Master Page.
Then I have a content page (aspx) that uses that Master Page.
Now, in the content page, I want to access a hiddenfield control that is placed in the user control.
How do I do that?
I tried the following but it returns null.
Master.FindControl("MyHiddenField")
Master.FindControl("MyUserControl1_MyHiddenField")
Thanks
In your content page (.aspx) place this code. It will make the Master Page strongly typed for the content page.
<%-- The Page directive goes here --%>
<%# MasterType TypeName="MyMasterClassName" %>
<%-- Rest of your code below.. --%>
In the Master Page code behind, place this code
public UserControlTypeName MyUserControl1
{
get {return myUserControl1; }
set {}
}
This makes the User Control instance public. You'll need to rename the ID of the user control to myUserControl1.
Then in your UserControlTypeName (or whatever the name of your class is for your User Control) you can make the inner controls accessible in the same manner we did on the master page.
public HiddenField
{
get {return myHiddenField;}
set {}
}
Obviously, rename the ID for MyHiddenField to myHiddenField to avoid a conflict.
Finally, this allows your content to access the controls within the user control that are on the master page through strong typing.
public void Page_Load(object sender, EventArgs e)
{
Master.MyUserControl1.MyHiddenField.Value="Hello, world!";
}
For further reference, see Working with ASP.NET Master Pages programmatically on MSDN.
If Microsoft Is Listening...
If for some reason a Microsoft ASP.NET developer is reading this answer, please consider doing something like this:
<asp:Button runat="server" scope="public" id="MyButton1 />
That would make it much easier than having to create wrapper properties to make inner controls publicly accessible.

ASP.NET Control Cannot Find Child Control in SharePoint Web Part

Host is SharePoint 2010, Using VS2010 .NET 3.5. I have custom ASCX controls living in Web Parts. The controls inherit from a POCO class that inherits from System.Web.UI.UserControl. This control has the following code:
protected override void OnPreRender(System.EventArgs evArgs)
{
var myliteral = Page.FindControl("myliteral");
base.OnPreRender(evArgs);
}
and every .ascx has this content:
<asp:Literal ID="myliteral" runat="server" Visible="false"><br /></asp:Literal>
I set a breakpoint to see if "myliteral" in the C# code would have a reference to the generated control, but it does not, it is coming out null. Why?
Thanks.
Page.FindControl doesn't look recursively in nested containers, so if myLiteral1 is in ascx used by webpart.
http://msdn.microsoft.com/en-us/library/31hxzsdw(v=vs.90).aspx

When isn't runat="server" used in asp.net?

When don't you need to use runat="server" in ASP.NET?
EDIT: Thanks for all the answers, but I was really thinking of runat="server" inside an <asp: tag.
Use the runat=server attribute when you're using ASP.NET controls, and/or you require programmatic access to those controls in your code-behind.
HTML controls don't require this attribute. It's useful if you have any HTML element like <span> <div>, or <table> when you want the ability to access them in code-behind.
<asp:Label runat="server" id="foo" />
<div runat="server" id="bar />
...
foo.Text = "Hello Label";
foo.Attributes["class"] = "baz";
You need to use runat="server" on any control that you want to be parsed as a server control.
Any element with runat="server" will be parsed into a server control in the Page herarchy. Anything else will be handled as plain text, and put in LiteralControl controls in the Page hierarchy.
The exception is elements that aren't real elements, but special tags within another server tag, for example ContentTemplate tags. They don't need a runat="server" because the containing control will parse them.
When you don't want the server side ASP.NET to render a server side variable against us.
Generally speaking you don't use it when you don't need to manipulate the DOM element at the server side e.g. which are only used for layout purposes.
Without runat="server" there would also be no other way to make html controls server side controls. It does look like an odd thing, because you can't do runat="client".
So in summation you can't leave it out on any ASP .Net controls ever and it was probably the easiets and cleanest way to find all server side controls for the developers who created ASP .Net Web forms.
source: http://mikeschinkel.com/blog/whyrunatserverforaspnetpart2/
Tag runat="server" indicates that the code contained within the script block will run on the server (and not on the client). On execution, ASP.NET will create server-side objects that contain this code as well as an instance of the Page class to contain the controls defined inside the page as instances of their given type (System.Web.UI.WebControls.Textbox, for example). This server-side object will be invoked on user request and will execute code in response to events.
Create Control in Runtime
I need one label in runtime that time don't need runat="Server" is not required
Example
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Label lblNew = new Label();
lblNew.ID ="lblnew";
lblNew.Text ="Test";
}
}
this code create label in runtime at page load event

Question about the "runat" attribute in ASP.NET?

I went through this thread but couldn't understand much. I am very new to ASP/HTML/Server-side programming.
I tried running this code on a .aspx file:
<form id="form1" action="Default.aspx">
<div>
<asp:Label ID="lblName"></asp:Label>
</div>
</form>
And I got an error when I tried to use this in the CodeFile:
protected void Page_Load(object sender, EventArgs e)
{
lblName.Text = "123";
}
"lblName does not exist".
But if I use runat="server" attribute with the label, then this code works.
Also, is there any concept of nesting the runat attribute. e.g, If I specify runat=server for the form above, will all my controls inside the form automatically be configured to run at server? How does this attribute work?
In which case would I be required to specify runat=server for the and for the tag? How does the server-side know that the label is inside the form if I don't have a form object at server side? Or am I missing something?
Any element marked with runat="server" lets the framework know that this will be a control on the server side. This article has more details:
Exploring the Runat Attribute
Nope, there is no such nesting available in ASP.NET, you have to specify "runat" to every control that you want to use in code behind and that is part of ASP.NET web library.
Because ASP.NET can only recognize difference between client side tag (the html that runs on browser) and server side tag with help of "runat"

Resources