Loading JS file using Url.Content in MVC 3 - javascript

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 <%: %>

Related

howto retrieve asp.net appSettings key from front-end .js file using knockout.js

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>

How to use Thymeleaf in a referenced JavaScript-File instead of between <script> tags

This is how we access [[${message}]] in JavaScript:
<script th:inline="javascript">
/*<![CDATA[*/
var message = [[${message}]];
console.log(message);
/*]]>*/
</script>
Since I don't want to use inline JavaScript, I have referenced a JavaScript file as followed:
<script type="text/javascript" src="/js/app.js"></script>
How can I access [[${message}]] in a my external JavaScript file, app.js?
Thymeleaf 3 introduced new template modes, one of which is javascript. So in addition to your TemplateResolver that returns html, you need to configure a new TemplateResolver that returns javascript resources instead. Then you'd create a controller as normal except it would be serving your javascript:
#Controller
public class JavascriptController {
#RequestMapping("/js/app.js")
public String greeting(Model model) {
model.addAttribute("message", "Here is a message.");
return "/where/your/js/is/app.js";
}
}
It would use the model as normal to pass variables to your external javascript.

How to read Session timeout value from web.config using javascript in JS file

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>

Using server side method in an external JavaScript file

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.

Tool / accelerator for improving adding css and script resources to MVC3 Razor pages

Is there any tool to make adding files to MVC3 razor pages faster?
I find myself having to drag script files onto the page to generate:
<script src="../../Scripts/rails.js" type="text/javascript"></script>
Which then i'll copy and paste
<script src="#Url.Content("~/Scripts/")" type="text/javascript"></script>
Then cut/drag the rails.js fragment into the new script statement. Then at some point after this hopefully I remember I need to clean up a whole bunch of duplicated and/or broken script links.
There has to be a better way than this that doesn't involve typing urls out manually.
Came across this blog post earlier today and ASP.NET MVC Best Practices (Part 1) and it's guidance shows
public static string Image(this UrlHelper helper, string fileName)
{
return helper.Content("~/assets/images/{0}".FormatWith(fileName));
}
public static string Stylesheet(this UrlHelper helper, string fileName)
{
return helper.Content("~/assets/stylesheets/{0}".FormatWith(fileName));
}
public static string NoIcon(this UrlHelper helper)
{
return Image(helper, "noIcon.png");
}
This seems like the optimal solution if you use a good layout scheme for your resources.
Edit: FWIW
public static string FormatWith(this string format, params object[] inputs)
{
return string.Format(format, inputs)
}
You can use T4MVC to get a compile-time validation your your links.
2.3. Strongly typed links to script files and static resources
T4MVC generates static helpers for
your content files and script files.
So instead of writing:
<img src="/Content/nerd.jpg" />
You
can write:
<img src="<%= Links.Content.nerd_jpg %>" />
Likewise, instead of
<script src="/Scripts/Map.js" type="text/javascript"></script>
You
can write
<script src="<%= Links.Scripts.Map_js %>" type="text/javascript"></script>
The obvious benefit is that you’ll get
a compile error if you ever move or
rename your static resource, so you’ll
catch it earlier.
Another benefit is that you get a more
versatile reference. When you write
src="/Content/nerd.jpg", your app will
only work when it’s deployed at the
root of the site. But when you use the
helper, it executes some server side
logic that makes sure your reference
is correct wherever your site is
rooted. It does this by calling
VirtualPathUtility.ToAbsolute("~/Content/nerd.jpg").

Categories