web.config in js - asp.net

How to get the web.config elements value in Javascript file?
I need the value of appSettings key's value in javascript file(not in aspx). What approach should I use to get this value?
web.config

On your aspx page you could do something like this.
<script type="text/javascript">
var keyName1 = '<%=ConfigurationManager.AppSettings["KeyName1"]%>';
</script>
Opening your entire web.config file to javascript could be a major security risk if you store things like database connection details or machine keys.

You can't get them directly in a javascript file - you can use server side scripting (ASP.NET) to output them values to javascript variables and pass those to functions that are in a file, but not dynamically in a javascript file.
You could create an HTTP module that will generate a javascript file dynamically - this would have direct access to the web.config and you will be able to insert values from it dynamically as you output javascript.

The least resource intensive would be to use something like filter chains in NAnt (or equiv in MSBuild—if it exists) to write the value to both your JS file and your web.config file.
This would prevent duplication of code (or configuration as it were).
The alternative (though a bit kludgy and more resource intensive) would be to put a script block above the script you need the value rendered dynamically from your aspx page using ConfigurationMangager.GetSection("web.config") in a way like this: http://schleichermann.wordpress.com/2009/01/15/dynamic-script-loading-in-html-head/

You should better get it from code-behind file and pass as a hidden value.

Using an expression builder is a little more flexible than the <%= %> tag, and there's one built in for accessing appsettings. Syntax is:
<%$ AppSettings:MyKey %>
Read more here.

Related

Accessing a control in asp.net content page through Javascript

I have a form in my content page for which I am doing some client side validations via Javascript. The Javascript behaves as expected if I place the JS code directly in the content page. But if I place the JS code in it's own file and try accessing that from the content/master page (through the script tag's src attribute), I get a run time error when the validation function in JS being called.
To be specific, I get the below error.
Microsoft JScript runtime error: Objected expected/required at this line - document.getElementById('<%=txtemailId.ClientID %>').value
txtemailId is in the content page.
Javascript code is placed in validation.js and accessed via master page.
The reason I guess is that when .net is parsing the files, it is unable to substitute txtemailId.ClientID with the client side value that would be generated later on. So, how should one go about it? Thanks!
The answer to this is quite simple.
Within your content page declare an in-line JScript variable, make sure this is above your tag.
<script>
var emailClientId = <%=txtemailId.ClientID%>;
</script>
Within your include.js file make use of the globally scoped emailClientId variable.
Obviously this is a bit clumsy because not all of the JScript code is contained within the include.js file, which makes it difficult to debug / diagnose as it is not clear specifically where the value is coming from. You should clearly comment / document this within your code to make maintenance of he codebase easier in the future.
You're right, the code <%=txtemailId.ClientID %> will only get replaced with the real client ID by ASP.Net if this code is in an ASP.Net file. So if you put this javascript in a separate .js file, ASP.Net will know nothing about it, and the code will not be parsed.
The easiest way to achieve this is to make the control IDs parameters of your functions. This way you can have the calling javascript code in your .aspx (or .ascx) file, along with the <%=txtemailId.ClientID %> code.
Standalone .js files are not run through the ASPX parser, so your expression is not being evaluated.
To solve the problem, you could set global variables (or function parameters, or something else) in the ASPX files with the IDs of the controls, then use them in the standalone .js file.
Alternatively, you could uses class names (which don't get mangled) instead of IDs. (This is very simple using jQuery)
An approach like this is best suited for something you want to achieve:
validation.js
var Validation = {
EmailId: null,
Validate: function() {
var email = document.getElementById(EmailId).value;
}
}
page.aspx
Validation.EmailId = '<%=txtemailId.ClientID %>'; //initialize
Validation.Validate(); //whenever you want to validate

How to have an asp.net ajax control automatically reference css files

I was wondering if its possible to have an ASP.NET AJAX custom usercontrol 'register' its use of CSS files like it does with JS files. ?
Eg: Implementing the IScriptControl interface allows for the GetScriptReferences() to be called by the Script Manager, is there a similar thing for CSS files?
No.
You could write your own methods to use embedded resources and generate html to write them to the page.
As a best-practice approach, though, I wouldn't recommend this. You should have a clear separation of style and markup. If you want to write a custom control that is dependent on a stylesheet, then I suggest that you provide a default css file along with your control.
EDIT (to answer questions in the comments)
You can run this code to add a reference to the CSS file to your page (at runtime). Note that because you're using the RegisterClientScriptBlock method, you can manage insert duplication. Here is an excerpt from the link for the method:
A client script is uniquely identified by its key and its type. Scripts with the same key and type are considered duplicates. Only one script with a given type and key pair can be registered with the page. Attempting to register a script that is already registered does not create a duplicate of the script.
StringBuilder sb = new StringBuilder();
sb.Append(#"<link rel=""stylesheet"" type=""text/css"" href=""");
sb.Append(this.Page.ClientScript.GetWebResourceUrl(this.GetType(), resourceName));
sb.Append(#""" />");
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "MyCSS", sb.ToString());

removing duplicate script from page

I am trying to make use of the yahoo exceptional performance rule : avoiding duplicate script
To do so i would like to be able to know whether or not a script was already added to the page before injecting it in the page. It looks like i can't figure what has been added in asp.net code behind unless i have a scriptmanager added to the page. but i would like to avoid using asp.net AJAX. From the description of the rule, it looks like it is something possible in php though.
Assuming that i can't do the check in my code behind, i was considering using jQuery $.getString function but it doesn't check before fetching the script. If i was to choose the javascript file, would i have to parse the whole http response in order to figure out which script was loaded on the page?
If the page is registering the scripts with the ASP.NET Page.ClientScript Register APIs then you can use Page.ClientScript.IsClientScriptIncludeRegistered. On the other hand, if you are using those APIs you don't really need to call it, since it already ensures only one of each is registered.
http://msdn.microsoft.com/en/us/library/system.web.ui.clientscriptmanager.isclientscriptincluderegistered.aspx
If the page just has regular ole script elements statically in the markup, and you need to detect if a script is loaded on the client side, you will have to get all the script elements on the page and look at their .src values. The thing with that is that some browsers automatically resolve that url to a full path, not just the one you declared. So, you can account for that in various ways -- you can just search for the end of the string being the script you want, or you can cause the url you want to compare with to also be resolved by setting it onto a dynamically created script element (which you never add to the DOM but is still resolved for you).
This is just off the top of my head, sorry if I get something wrong:
var s = document.createElement("script");
s.src = "foo.js";
var loaded, scripts = document.getElementsByTagName("script");
for (var i = 0; i < scripts.length; i++) {
if (scripts[i].src === s.src) {
loaded = true;
break;
}
}
if (loaded) {
// this script is already loaded
// assuming you dont have multiple copies in different locations
}
You don't need to use any client-side scripting to do this... you can do this in your code behind using the ClientScriptManager without needing to make use of ASP.NET AJAX (I think you're confusing ClientScriptManager with ScriptManager*) in your control/page just use:
ClientScript.RegisterClientScriptInclude("some-script", "myScript.js");
or from your user controls:
Page.ClientScript.RegisterClientScriptInclude("some-script", "myScript.js");
This will use the key "some-script" & only register one copy of the script on the page.
*To be clear I think the confusion is arrising from the difference between these:
ClientScriptManager if a server-side helper class which is used to manage client side scripts (in other words its whole purpose is to do exactly what you are trying to do). It is accessed via the Page's ClientScript property.
ScriptManager is a Control used to aid client side Ajax scripting in ASP.NET AJAX
(hell I even confused myself & gave the wrong example code initially)
well that wouldn't actually work in a master detail scenario with multiple web user controls.
Then you wouldn't have control over who has to do the script initialization if the web user control is dynamic.
It's easier to link once, but a developer would have to weigh his options between ClientManager and using a script load.
yeah you have to parse the whole response...
why don't you create a javascript file and put all of your javascript there and then import that javascript file in your code??? in this way you can get rid of duplicate script insertion.

get all script files in asp.net page

is there a way to find all script files added to a page in asp.net code behind? i am trying to add script dynamically but would like to check first if it already exist on the page.
AFAIK, no. Other developers can just add <script> tag on the fly and not through the .NET objects.
If you ensure that everyone uses ScriptManager, then you can use GetRegistered* methods on the object.
If it's inline script, you can use ClientScriptManager.RegisterClientScriptBlock which uniquely identifies a script by its type and key and will make sure it's registered only once.

Duplicate html in a ASP.NET project

I have some HTML that will need to be duplicated in a number of places. If I externalize this to a text file and include it in the ASPX page, it would work but I will need to pass a parameter to this HTML (ClientID)
Without having to create a User control, is there a lighter way of doing this?
I would use a master page for this. Depending in the version of the framework(2.0+) Nested Master Pages are also an option.
You could just have a raw aspx file with the HTML inside:
<%
If (Request.QueryString["ClientID"]) {
// Do Something
}
%>
<p>HTML File Contents</p>
Then you could either server-side include the file or server.execute the file.
You may want to clarify how you pass a ClientID to "HTML", because it sounds like you're doing server-side processing to generate your HTML, which is a classic case of Ajax. I would recommend using JQuery to achieve this.
Perhaps standard #Includes still work, but TBH I haven't found any downside to master pages (as yet). This is what they were designed for.

Resources