How to reference server side controls in JQuery ASP.NET? - asp.net

What is the recommended approach to reference ASP.NET server side controls in JQuery?Currently I use something a mix of server+client side
$('#<%=txttest.ClientID %>').focus();
I read somewhere it is not a good approach and it slows down things somewhat.

It does not slow things at all from the selector point of view.
it will slow down things because this code will have to be inside the HTML and not inside the JS which can be compressed and minified.
As a .net developer in my past (not that far), I always prefered selectors to refer classes then ID's.
something like
$("input.textInputClassName").val('this is the new value');
because in .net you have no control over the ID's (ARGHHHHH) then you should select using classes (IMHO of course)

$('#<%=txttest.ClientID %>').focus(); this code works only when you have written java Script in the same .aspx page but when your using separate javascript file for your page then this code will not work.
The approach what i prefer is if the controls are static then i will specify the
name
Ex : $('#txttest').focus();
or if the controls were created dynamically then i will register the script or add the attributes to the page
Ex : BtnDailog.Attributes.add("onclick","$("#divMsg.show()");

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;
}
}
}

How to use jQuery scripts with MasterPage/Content page scenario?

I have created a great stand-alone web form in asp.net utilizing many jQuery features and CSS. It works fine. When I re-create it as a web content form as part of a MasterPage, my jQuery and javascript is completely ignored.
I am referencing the pertinent jQuery and CSS in my of the MasterPage. I have a content placeholder at the bottom of the masterpage called "ScriptContent". In my content page, this is where I plug in the various jQuery methods and javascript.
When I view the page source everything is there. However, it's all being ignored so to speak. What am I doing wrong?
Probably the issue is that when your page is loaded as a content page within a masterpage, the ids of all of the elements are altered to reflect what content page they are in. Thus the ids you are using in jquery won't work.
Options I can think of include:
setting the ids used by jquery programatically from asp.net code (using the clientId of the element)
having your jquery selectors reference some other attribute of your element, such as class (which is unfortunately a bit slower)
I would match the source output of the working version against the output of the non-working version.
Obviously, there's something being rendered out from ASP.NET differently. Getting the difference would tell you what.
Since I have no details, I can only guess...but it sounds like you may have left out some $(document).ready() type functionality to kick off your script somewhere.

ASP.NET - What is the best way to keep jquery from cluttering up my ASPX files?

I'm starting to use more and more jquery. I'm working with dialogs, and each dialog (including javascript) is taking upwards of 20-30 lines of code. There's a few pages where I'll have over 5 dialogs. This gets ugly fast. I haven't even begun to get into sliding interfaces or calendar controls yet.
I have more of a PHP background... and in these situations i'd be moving things to an "include" file. I can see that working for items such as jquery-dialogs in ASP.NET, but when I start adding jquery features to actual ASP.NET form items.. that won't be an option (as far as I know).
How can I keep the extra javascript and extra floating divs from cluttering up my ASPX files too bad?
I'm prepared to partition the ASPX file into well documented, distinct sections... this just results in a very "tall" file. Any better solutions?
Thanks.
You could put the javascript code into separate js file(s). You then reference the js file(s) in your page.
I'm not sure how you're structuring your .NET and your markup, but I'd be using external JavaScript files to handle all of that, no inline JavaScript. That's how we work in here, and no issues so far, with a nice separation of markup, CSS, JavaScript, and .NET.
If you have specific types of dialogs, then use classnames on your markup, then in the JavaScript include files use classes as your selectors to create the dialogs.
Let's see...
Since you are using jQuery, you must know the script src syntax already to include javascript files, so I assume this is not the problem :).
For those pesky crazy looking control ID that ASP.NET create...
cache them in a JavaScript global variable at the end of the page... like:
<script>
ControlIDs = {
SaveButton = '<%=SaveButton.ClientID%>',
BlahTextBox = '<%=BlahTextBox.ClientID%>'
}
</script>
And in your separate jQuery code file, do...
$(ControlIDs.SaveButton).Whatever()
3. Instead of using the ASP.NET control ID, maybe you want to try using the CSS Class Name as selector in jQuery to get to a particular control (treat class name as control Id), might not be an ideal idea, but it could work.
Any of these should allow you to do some degree of Javascript separation.

De-cluttering ASP.NET javascript

I'm just getting into ASP.NET Been avoiding it for years as I'm a desktop application advocate.
Anyway, I was wondering if there's a way to stop the generated html being so cluttered with javascript. Is there a way to make the generated script go into a referenced js file rather that inline with the page.
Look into ASP.NET MVC - it is an alternative to WebForms and tends to have less clutter.
Are you sure you're using code-behind?
When you add a new page, make sure you check "Place code in a separate file", otherwise all your server-side code will be on the page (even tough it won't show up for the end-user)
If you're using code-behind but it still has a lot of javascript code in the page (maybe you're using ajax?) I'd suggest you don't use the .NET ajax controls, just do all the ajax by hand, using jQuery or Prototype. It's fast and it'll be as lightweight as it can be.
Check out ClientScriptManager.RegisterClientScriptInclude.

Register Startup Script Control

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,

Resources