In a c# aspx project.
I can reach a static method on client side with importing my namespace at the beginning part of the page, as follows.
<%# Import Namespace="utl=portal.library.Utilities" %>
And than in can use that on client side of the same asxp page like.
<script type="text/javascript">
var categoryPage;
categoryPage = '<%= utl.getcategoryName().ToString() %>';
</script>
My question is, can i use that '<%= utl.getcategoryName().ToString() %>' in an external javascript file ?
Is it possible something like that ?
<%# Import Namespace="utl=portal.library.Utilities" %>
<script src="/scripts/trial.js" type="text/javascript"></script>
and in the trial.js file
var categoryPage;
categoryPage = '<%= utl.getcategoryName().ToString() %>';
thanks in advance..
I don't think so, because the external .JS file wouldn't be processed by ASP.NET and therefore wouldn't have access to those kinds of variables.
I don't think you can but you could instead try to pass the server side variable as a parameter to a JS function in the external JS file.
You can create a .aspx file that only outputs Javascript instead of HTML. As long as you set the Content Type to application/x-javascript in the code behind, it will work.
For example, create Test.js.aspx. Then, in the code behind for Test.js.aspx.cs:
protected void Page_Load( object sender, EventArgs e )
{
Response.ContentType = "application/x-javascript";
}
protected string GetMessage()
{
return "Hello, World!";
}
In the Test.js.aspx file:
window.onload = function() {
var msg = <%=GetMessage() %>
alert(msg);
}
Now, it is true that the Javascript running on the client can't call C# functions running on the server. You would need AJAX for that. But you can certainly use this pattern to generate Javascript that make use of ASP.NET when it is generated.
Related
I have an asp.net backend application and i am using web.config and other files to store configuration keys.
I have a front-end built with javascript files using knockout.js.
We would like to know how can we retrieve key value from web.config in backend and read this value in front-end using javascript and knockout.js.
Is there a simple way to do this ???, Views are javascript files and not asp.net web pages
You can render values directly to JavaScript <script> in your view/HTML/page files.
And then any JavaScript (with or without Knockout, jQuery, React, Redux, AngularJS, Angular2+, whatever) can access those values immediately.
IMPORTANT: Be sure to correctly JS-encode (not HTML-encode!) C#/.NET String values when rendering them as JavaScript string literals! ...otherwise backslashes and quotes will be rendered literally which will break your rendered <script> element and likely introduce significant XSS vulnerabilities.
In ASP.NET 4.x, use HttpUtility.JavaScriptStringEncode to ensure C#/.NET string values are correctly and safely encoded to JavaScript strings.
In ASP.NET Core you can continue to use HttpUtility.JavaScriptStringEncode (in the now almost empty System.Web.dll System.Web.HttpUtility.dll in .NET Core 2.x or later) however now the preferred API in .NET is System.Text.Encodings.Web.JavaScriptEncoder's Encode method (tip: use JavaScriptEncoder.Default.Encode).
Note that HttpUtility.JavaScriptStringEncode can optionally add delimiting quotes for you, but System.Text.Encodings.Web.JavaScriptEncoder never renders outer quotes.
For Razor .cshtml in ASP.NET MVC and ASP.NET 4.x WebPages:
(I assume your <head> is in _Layout.cshtml)
#using System.Configuration
#using System.Web.Configuration
<html>
<head>
<script>
var myAppSetting = '#( HttpUtility.JavaScriptStringEncode( WebConfigurationManager.AppSettings["myAppSetting"], addDoubleQuotes: false ) )';
</script>
</head>
<body>
</body>
For ASP.NET WebForms .aspx/.ascx/.master and/or ASP.NET MVC 1.x and 2.x using the WebForms ASPX View Engine:
(I assume your <head> is in Layout.master)
Use <%= instead of <%: to render directly, btw, as we don't want to HTML-encode this JavaScript string literal.
<%# Import Namespace="System.Configuration" %>
<%# Import Namespace="System.Web.Configuration" %>
<html>
<head>
<script>
var myAppSetting = '<%= HttpUtility.JavaScriptStringEncode( WebConfigurationManager.AppSettings["myAppSetting"], addDoubleQuotes: false ) %>';
</script>
</head>
<body>
</body>
For ASP.NET Core MVC's Razor .cshtml views:
Use #inject IConfiguration to get immediate access to .NET Core's appSettings.
You can use either HttpUtility.JavaScriptStringEncode(...) or System.Text.Encodings.Web.JavaScriptEncoder.Default.Encode(...) in ASP.NET Core (including .NET 6).
Don't forget outer-quotes!
Use Html.Raw() to render the JS literal string. Do not use the normal Razor "write" syntax (i.e. #( value ) or #value) because it will HTML-encode your JavaScript, which you don't want.
Like so:
#using System.Text.Encodings.Web
#inject IConfiguration Config
<html>
<head>
<script>
var myAppSetting = '#Html.Raw( JavaScriptEncoder.Default.Encode( this.Config.GetValue<String>("appSettings:myAppSetting") )';
</script>
</head>
<body>
</body>
Note that if you want null values from your appSettings.json to appear as JavaScript null literals then you need to do that manually - you can use a #functions method to handle this, like so:
#using System.Text.Encodings.Web
#using Microsoft.AspNetCore.Html
#inject IConfiguration Config
#functions{
public HtmlString GetAppSettingJSString( String name )
{
if( name is null ) throw new ArgumentNullException(nameof(name));
String? appSettingValue = this.Config.GetValue<String?>( "appSettings:" + name );
return ToJSStringLiteral( appSettingValue );
}
private static readonly HtmlString _nullLiteral = new HtmlString( "null" );
public static HtmlString ToJSStringLiteral( String? value )
{
if( value is null ) return _nullLiteral;
String jsStringLiteralChars = JavaScriptEncoder.Default.Encode( value );
return new HtmlString( '"' + jsStringLiteralChars + '"' );
}
}
<html>
<head>
<script>
var myAppSetting = #Html.Raw( this.GetAppSettingJSString( "myAppSetting" ) );
</script>
</head>
<body>
</body>
So now the <script> above will be rendered as either this:
<script>
var myAppSetting = "foobarbaz";
</script>
...or this:
<script>
var myAppSetting = null;
</script>
Any script (except ES Modules, I think?) can access myAppSetting via the implicit global (aka window) object, as all top-level var declarations become global properties.
So like so:
<script>
document.addEventListener( 'DOMContentLoaded', function() {
alert( "myAppSetting: \"" + window.myAppSetting + "\"" );
} );
</script>
I have Durandal SPA which uses url.config.js file among different views. Bunch of urls to services are stored there.
Code for clarity:
define([], function () {
var serviceBaseUrl = 'http://localhost/Service/api/';
var portalPortalUrl = 'http://localhost/Portal';
});
And whenever I need to deploy my app, or run it with different IIS settings, I need to manually change this urls in code.
What I want:
To store them in Web.config file so I can have different configuration for debug and release modes.
I am using MVC 5 Razor views only for rendering bundles and initial content, all client side logic placed in Durandal folder.
I have only found solutions using ASP.NET ConfigurationManager like so:
function ReadConfigurationSettings()
{
var k = '<%=ConfigurationManager.AppSettings["var1"].ToString() %>'
alert(k);
}
Or, for Razor:
#System.Configuration.ConfigurationManager.AppSettings["myKey"]
It's cool, but not my way.
Maybe it's possible to auto generate my urls.config.js file based on Web.config keys?
Thank you in advance.
If needed, here is my project structure:
- App //Durandal SPA
- Controllers
- Views //Only render initial view
- Web.config
You can use JavaScriptResult
Sends JavaScript content to the response.
Code, Controller Action method
public JavaScriptResult Config()
{
var script = string.Format(#"var configServiceBaseUrl = {0};", ConfigurationManager.AppSettings["var1"]);
return JavaScript(script);
}
In the page header(I would load the file first), You can define:
<script type="text/javascript" src='#Url.Action("Config", "Controller")'></script>
Now configServiceBaseUrl is Global JavaScript variable which you can use anywhere.
So you can use configServiceBaseUrl in url.config.js like
define([], function () {
var serviceBaseUrl = configServiceBaseUrl;
});
Adding to satpal, for SPA application such as angular js
For SPA's, such as angular you can use below code in your index.html as
<script type="text/javascript" src='/Controller/config'></script>
Can anyone please guide me to read the value of Session timeout value using javascript contained in a .js file.
I need to access the value in a javascript file and process the value.
I tried to follow the below approach in a test.js file but it is not working:
var sessionTimeout = <%= Session.Timeout %>;
alert(sessionTimeout);
Your problem is that .JS files are not executed so they do not contain the Session.Timeout variable.
You can do two things:
Include your javascript directly in your ASP/ASPX page that does have the code being executed.
Register your JS script in your code.
Registering your JS
See: http://msdn.microsoft.com/en-us/library/aa479011.aspx#aspnet-usingjavascript_topic07
Page.RegisterClientScriptBlock("MyScript", _
"<script language=javascript src='MyJavaScriptFile.js'>")
I have share m code which I use for connection string from this code you can replace logic for session.
<script language="javascript" type ="text/javascript">
function ReadWebConfig()
{
var strCon = '<%=ConfigurationManager.ConnectionStrings["MysqlCon"].ConnectionString %>'
alert(strCon);
var strTemp = '<%=ConfigurationManager.AppSettings["WordTemplate"].ToString() %>'
alert(strTemp);
}
</script>
Can I get print data in my .js files before sending them to the client? I want to be able to print the session id into a variable to use in getting around the flash cookie bug. Here's my code:
//Add our custom post-params
var auth = "<% = If(Request.Cookies(FormsAuthentication.FormsCookieName) Is Nothing, String.Empty, Request.Cookies(FormsAuthentication.FormsCookieName).Value) %>";
var ASPSESSID = "<%= Session.SessionID %>";
this.setPostParams({
ASPSESSID: ASPSESSID,
AUTHID: auth
});
That shows up exactly the same way in my js file. I want the server to process the code!
You can not include the .NET markup in the js file. You can use an ashx file to generate a dynamic script files if you really want to do it.
Why write it in the JS file? Write it to the page with ClientScriptManager.RegisterClientScriptBlock so the JavaScript can be cached properly. The script will still be able to access the variable in the page as long as the included script appears after the code.
I think you want to use immediate if. Like:
var auth = "<% = iif(Request...
I am trying to load a javascript using the following in MVC 3, but the script does not load:
<script src="<%: Url.Content("~/Content........
If I load using the following then it works:
<script src="../../Content......
What could be the problem
When loading Scripts, I tend to use a custom helper instead.
The code below does this, and has an additional boolean parameter that can be used when the script is not local to your applicaiton, and on a CDN for instance.
public static MvcHtmlString Script(this HtmlHelper helper, string src, bool local = true)
{
if (local) {
src = VirtualPathUtility.ToAbsolute("~/Scripts/" + src);
}
TagBuilder builder = new TagBuilder("script");
builder.MergeAttribute("src", src);
builder.MergeAttribute("type", "text/javascript");
return MvcHtmlString.Create(builder.ToString(TagRenderMode.Normal));
}
You can then call the helper in your view like this:
<%: Html.Script("jquery.validate.min.js") %>
or:
<%: Html.Script("http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.2.js", false) %>
You should first Add an Assembly(namespace)
System.Web.Optimization
then simple render any Script like this.
#Scripts.Render("~/Content/Scripts/test.js")
do not forget to include namespace first
Using System.Web.Optimization;
Note <%: renders an HTMLString and you do not want that. <%= renders a string.
Below should work.
<script src="<%= Url.Content("~/Content........
see this question for details ASP.NET <%= %> vs <%: %>