Register Startup Script Control - asp.net

I am looking to make a web control where I can register client startup scripts inline with my aspx because I hate registering in the codebehind!
An example of what I have so far:
<Ben:StartupScript runat="server">
var form = document.getElementById("<% =form1.ClientID %>");
</Ben:StartupScript>
Currently, I am overriding the OnPreRender method of the control, rendering the contents of the control to a string and then manually registering that string as a startup script using ClientScript.RegisterStartupScript on the Page. I also override the Render method in order not to render the control. I should also note that I have the ParseChildren attribute set to false and the PersistChildren attribute set to true.
All seems to be working well, but my control allows other web controls inside it (such as Button). Apart from being unintuitive, this can result in runtime errors. I would love to be able to clear the controls but this is impossible given the <% ... %> code block.
So, is it possible to prevent developers from embedding child controls whilst still allowing code blocks?
Also, is this idea any good or is it fundamentally flawed? Lol.
Thanks a bunch,
Ben

it sounds like a good idea, but if you spend too much time fighting the inherited/default behaviors then it may be more trouble than it's worth
if this is a one-shot issue, a cheap-hack solution is to just directly embed your scripts in the header of a master page ;-)
on the other hand, allowing developers to embed their own scripts as children of your web control might be useful

If you are using master pages, add another control in your section. That way you can easily add css/js to your headers in your child pages.
ClientScript.RegisterScript is mostly for user/server controls,

Related

Reusing ASP.NET code in multiple pages

Is there a way to reuse a piece of ASP.NET code (that tag-based code, not the code-behind) in many different pages? For example I have a <div> with some contents in it that appears in 5 different pages of my site. I'm looking for a technique through which I could save this <div> in a separate web-content file so to speak, with maybe a different extension like MyDiv.ASPC and could then do a server-side tag anywhere in a webpage like:
<asp:Import href="~/MyDiv.aspc" />
and ASP.NET would inject the entire content of this file at that point where this tag appears.
I thought of creating a user control for this, but I'm not sure if a user control always injects precisely what is written in its body, or could there sometimes be unwanted tags generated by user control itself.
Or are there existing better ways of doing this?
Edit
About Master Pages, they are far away from what I'm looking for. They are actually good for a common basic layout of your website. My idea is quite opposite of that. My pages do not have a common layout; it is just that they have one common <div>. It is more closely fulfilled by a UserControl.
For UCs, my fear is that they generate more than what is written in their body, whereas what I'm after is a simple text injection. To put it technically, what I'm looking for is basically a preprocessor step (kind of #include thing in C++) rather than a compiler step, if you see what I mean.
You need to use ASP.NET User Controls, as these are specifically created to be the solution to the problem you are describing. For more information, see MS Documentation.
From their documentation...
In addition to using Web server controls in your ASP.NET Web pages,
you can create your own custom, reusable controls using the same
techniques you use for creating ASP.NET Web pages. These controls are
called user controls.
A user control is a kind of composite control that works much like an
ASP.NET Web page—you can add existing Web server controls and markup
to a user control, and define properties and methods for the control.
You can then embed them in ASP.NET Web pages, where they act as a
unit.
An empty userControl would do just that - nothing. A user Control just adds it's contents to the page, or usercontrol hosting it. It adds nothing extra.
UserControls give you a nice easy page fragment type approach to reusing content. They work great within a project & most people use them for just that.
If you wanted to make something more reusable across projects, you could write server control. It's more involved, but much more reusable. Google should be able to find you many tutorials on how to do this.
Ran a short test. User Controls do not enter extra tags as long as you don't place any Runat="Server" tags in it, so this would indeed be a solution I guess.
You can also read output from a cache object where you would read your files.
So
<%= Static.ContentXyz %>
would mean:
public static class Static
{
public static string ContentXyz
{
get
{
string s;
if (!this.cacheDictionary.TryGetValue("ContentXyz", out s))
{
s = File.ReadAllText(Server.MapPath("ContentXyz.html"));
this.cacheDictionary("ContentXyz", s);
}
return s;
}
}
}

Is it a good idea to use plain HTML instead of ASPX

I'm developing an ASP.NET website. Sometimes some modules contain so few content that I present them inside a jQUeryUI dialog and communicate with the server via AJAX. I keep those contents inside a separate file and load them to a jQueryUI dialog according to the appropriate module.I was wondering if it's a good idea to have that content as a plain HTML elements instead of asp ones. Somehow I thought maybe this would reduce the overhead the conversion from asp elements to html elements can cause.
I'd allways go with the aspx Page, because a dynamic Page is more work at the beginning but in the end it almost ever saves time.
Specially when your not sure of the content that will be shown there, it is better.
And for the one reason i do it, is to have everything the same.
One style one way to code.
I'd say this is probably premature optimization. The overhead of an aspx page is in almost all cases negligible. I believe it's more likely that you will some day need to put dynamic things in that page, in which case you would have to convert the html file to an aspx, and change the url for your ajax dialog - which will cost time/money.
If you have aspx pages, or ascs user controls that you do not actually use/run any code, you can set the AutoEventWireup the EnableViewState, and maybe the EnableSessionState to false and stop the calling of the PageLoad and the rest functions and reduce the overhead. So on top of the controls you declare:
<%# Control AutoEventWireup="false" EnableViewState="false" ...
or for page:
<%# Page AutoEventWireup="false" EnableViewState="false" EnableSessionState="false" ...
The disable of the session is let the pages loads in parallel, the disable of the EnableViewState is reduce the size, the AutoEventWireup is reduce the callback hooks and calls.
In general you can use what ever you wish - if your pages can work, but if you like to keep it robust and easy to change or update, or add new functionality in the future, then use dynamic aspx pages.
Similar question: Master page and performance

Preventing page lifecycle for one control

I'm using a file manager-type WebControl that does lots of postbacks. It's placed inside a Page that is relatively complex. I would like to prevent the WebControl from causing the whole Page to go through the lifecycle. An UpdatePanel helps a little, but not enough.
Is there any way to isolate the WebControl from the rest of the Page? The only way I can think of is sticking the WebControl in a separate Page and creating an iframe in the original Page. Unfortunately that also means my WebControl properties/settings are no longer in the original Page. If I want two instances of the WebControl with different settings, then I have to create a Page for each setting and reference the correct one in my iframes. Not quite as "drag & drop" as I would like. Any other suggestions?
Hard to tell, you can't prevent a control from going through lifecycle; is there anyway to identify though, that during a certain page postback, you prevent the code from running in each event handler by doing something like:
if (_shouldNotRun == true)
return;
//Event handler code
Essentially, figuring out some way to indicate whether the control should run may be an option. IFrame would work, but yes you have to deal with the issues you mentioned. Can you give more detals to the problem?
HTH.
Not 100% sure what events possible to override that are called on PostBack. A good source for the Life Cycle of a page (http://msdn.microsoft.com/en-us/library/ms178472.aspx)
But it sounds as it would be better to remake your control to create Ajax webservice requests for the functions that are possible to prevent most of the postback's?
Cheers,
Stefan

Alternatives to ASCX User Control without a server-side form?

I've got an ASP.NET 3.5 Web Forms application in which a large chunk of code needs to be duplicated between a few different pages. Sounds like the ideal candidate for a user-control right? Problem is, this cannot be contained within a <form runat="server"> because it contains a client-side form of it's own.
There are no runat=server controls or postbacks or anything that really need that webform - think of it just as a chunk of HTML with a few basic <% %> tags. I'd just want to set a property on the control when it's loaded, so that it knows what to output. This is purely an exercise to make the code easier to maintain.
Before I resort to using an oldskool <!--#include-->, is there some better way of doing this?
You can still use a normal user control. Just don't rely on viewstate and postbacks and you shouldn't have any problems.
<%=Response.Write(File.ReadAllText(Server.MapPath("~/includes/filename.ext")))%>
Something along those lines, anyway.
Edit: Same functionality as a server side include, but if I'm not mistaken, enabling the SSI syntax requires an IIS change, where as this wouldn't.
Edit 2: I didn't see the note that your include contains asp.net code. This would obviously only work for client side code only. My mistake.
You can have as many form controls as you want but only one can have runat="server".
Some other techniques:
http://webproject.scottgu.com/CSharp/UserControls/UserControls.aspx
http://weblogs.asp.net/scottgu/archive/2005/08/28/423888.aspx
I'd still make it a control. The <% %> stuff could be labels/literals for more flexibility, and as soon as you get done saying there are no postbacks needed, you'll need them. Best to set up the other pages to include it as a control now for easier changes later. Heck - you could even take advantage control-level caching!

In ASP.net is it better to use Server Controls within the ASPX page or create them dynamically in the code behind?

I generally prefer to add controls dynamically, like table and generic html controls, to the ASPX page, rather than add them in the ASPX page and set the properties dynamically.
Which approach is considered "better practice"?
Also is using generic html controls dynamically a better practice than outputting formatted html strings to an asp:literal?
Keep them in the .aspx
Adding them dynamically leads to view state issues and they must be added in each post pack. I ran into this when building a user generated forms app. I Broke down and used the controls visibility property as a work around. That said if your eliminating view state and post back from your app these may not be issues for you.
https://web.archive.org/web/20211031102347/https://aspnet.4guysfromrolla.com/articles/092904-1.aspx
Since in both approaches you end up with a set of code that adds controls and assigns values to their properties then the best practice is the approach that is the most readable.
Due to complex decision logic it may be better to do it all yourself on the hand for fairly static control layout where only the properties need modifying placing the control in the ASPX would be more straight-forward.

Resources