How do we concat a string in a View file in MVC - asp.net-mvc

I am trying to concat a string in a view file for MVC.
How do we do that?
I am trying to use an application key value as the value:
<%=ConfigurationManager.AppSettings["googleMapKey"].ToString() %>
I would like for it to go where the value of the Key is at:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyC6P8xxxxxxxxxxxxxxxxhNMwLG0M&sensor=false"></script>

Assuming you are using the aspx view engine you could use this:
<% string key = ConfigurationManager.AppSettings["googleMapKey"].ToString(); %>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=<%= key %>&sensor=false"></script>
and if you are using the Razor view engine then:
#{ string key = ConfigurationManager.AppSettings["googleMapKey"].ToString(); }
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=#key&sensor=false"></script>

Do it this way:
<script type="text/javascript" src="<%= string.Format("https://maps.googleapis.com/maps/api/js?key={0}&sensor=false",ConfigurationManager.AppSettings["googleMapKey"].ToString()) %>">
You are in fact using "string.Format" command which by the way, I believe is one of the most beneficial command in .Net.

Related

Why doesn't angularjs code render when controller is referenced?

I've created a new asp.net MVC app in VS.NET 2013. In _Layout.cshtml, I have a reference to the angularjs library (Google developer site). I also define a controller called "con1" and create a variable.
_Layout.cshtml:
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.4/angular.min.js"></script>
<script type="text/javascript">
function con1($scope) {
$scope.somestring = "some string";
}
</script>
Index.cshtml:
<div>
{{1+1}}
</div>
The above works fine and renders the result of "2".
When I change the div to the following and start trying to access the somestring variable in the controller, I get the actual AnguarJS code rather than the result.
<div ng-controller="con1">
{{1+1}}
</div>
Output: "{{1+1}}"
Any idea why adding the controller reference breaks it? This seems to be VS.NET specific. I have a jsfiddle here that works fine: http://jsfiddle.net/jpswdzxu/. That is basically the output from the VS.NET project.
You need to define the Angular Application, or it won't work:
<script type="text/javascript">
var myApp = angular.module('myApp',[])
.controller('myAppCtrl', function($scope) {
$scope.somestring = 'teststring';
});
</script>
Then, the HTML should be:
<body ng-app="myApp">
<div ng-controller="myAppCtrl">
{{somestring}}
</div>
</body>
Or, using your jsfiddle, it would be:
<div ng-app="myApp" ng-controller="myAppController">
{{1+1}}
<br>
{{somestring}}
</div>
and:
angular.module('myApp',[])
.controller('myAppController', function ($scope) {
$scope.somestring = "some string";
});
Good Luck!

How do you play an audio file on keyboard keystroke?

I'm developing a space based environment in Rails 4 and want to play a small sound file every time a key is pressed while the user is filling out a form. In other words, every keystroke would make a small clicking sound while typing.
I'm also looking to have this solution hosted remotely possibly in the assets folder, so the user does not have to install some third party application or software to make it happen.
Is this even possible with rails? Or, what other frameworks/libraries/technologies would I need to incorporate to accomplish this with Rails, and any examples or links to examples would be appreciated. Thanks.
<!-- Sound Manager -->
<link rel="stylesheet" type="text/css" href="/soundman/demo/360-player/360player.css" />
<link rel="stylesheet" type="text/css" href="/soundman/demo/flashblock/flashblock.css" />
<!--[if IE]><script type="text/javascript" src="/soundman/demo/360-player/script/excanvas.js"></script><![endif]-->
<!-- I'm not certain which of the following .js includes are actually required, I included them all and it works, however, some of these includes may not be necessary for the most basic of implementations. Please update if you find the minimal required includes -->
<script type="text/javascript" src="/soundman/demo/360-player/script/berniecode-animator.js"></script>
<script type="text/javascript" src="/soundman/script/soundmanager2.js"></script>
<script type="text/javascript" src="/soundman/demo/360-player/script/360player.js"></script>
<script type="text/javascript">soundManager.setup({url: '/soundman/swf/'});</script>
<script type="text/javascript">
function hoverCategory() {
soundManager.setup({
url: '/soundman/demo/_mp3/hover01.wav',
onready: function() {
var mySound = soundManager.createSound({
id: "a2", // <----------- Make this unique or you might run into conflicts
url: '/soundman/demo/_mp3/hover01.wav' // <------- mp3's work as well
});
mySound.play(); // <------------- lots of cool options on mySound, play() being just one of them
},
ontimeout: function() {
}
});
}
</script>
<!-- Onclick -->
<%= f.check_box :radial, :onclick => "Javascript:hoverCategory()" %>
<!-- Onmouseover -->
<%= f.submit :onmouseover => "Javascript:hoverCategory()" %>
<!-- Onkeypress -->
<%= f.text_field :status, :onkeypress => "Javascript:hoverCategory()" %>

Syntax for partial parameters

I cannot seem to get the syntax right for parameters to partials. The following keeps getting a syntax error: Uncaught SyntaxError: Expected buffer, comment, partial, reference, section or special but "{" found dust.js line 60.
<html>
<head>
<script type='text/javascript' src='/static/js/jquery.js'></script>
<script type='text/javascript' src='/static/js/dust.js'></script>
<body>
<p>TEST</p>
<p class='area1'>content_stuff</p>
<script>
$(document).ready(function() {
dust.loadSource(dust.compile("THE PARTIAL IS: {>inner foo='bar' /} AND THATS ALL", "outer"));
dust.loadSource(dust.compile("INNERPART", "inner"));
dust.render("outer", {}, function(err, out) {
console.log(out);
$(".area1").html(out);
});
});
</script>
</body>
</html>
Stick with the latest linkedin release. I think you may need double quotes around bar param value though.

Rails - use code(css, js, html) from server on client side

I had a application rails built with bootstrap and simple form.
Here I have to show the UI patterns how they actually look like. That means I have to show the
patterns like menu bar, accordian patterns examples in my application. For that I am storing the pattern code html,css,js in database.
Here my requirement is I have to show the actual code pattern view from the stored record(css,js,html) without any css/js conflicts.
How can eneter the html,css,js code dynamically in a partial or page to show that
in a fancybox in rails.
Thanks for the help in advance.
just use html_safe or raw to render your content as a normal string on views. For instance:
in your controller:
#x = YOUR_CODE_FROM_DB
in your view:
<%= #x.html_safe %>
# <%= raw #x %> is also ok in this case
NOTICE: you can use html_safe on models, but raw is declared on a helper, so you can just use it on controllers and views.
-- edit --
more example:
on controller:
#hello = 'alert("hi");'
#body = 'body{ background: red; }'
on view:
<script type="text/javascript" charset="utf-8">
<%= raw #hello %>
</script>
<style type="text/css" media="all">
<%= #body.html_safe %>
</style>

How to safely embed JSON with </script> in HTML document?

In a Rails 3.1 app, how can I safely embed some JSON data into an HTML document?
Suppose I have this in a controller action:
#tags = [
{name:"tag1", color:"green"},
{name:"</script><b>I can do something bad here</b>", color:"red"}
]
And this in a corresponding view:
<script type="text/javascript" charset="utf-8">
//<![CDATA[
var tags_list = <%= #tags.to_json %>;
// ]]>
</script>
Then I get this in resulting HTML:
var tags_list = [
{"name":"tag1","color":"green"},
{"name":"</script><b>I can do something bad here</b>","color":"red"}
];
which triggers a SyntaxError: Unexpected token & in Chrome
If I remove the Rails' default HTML escaping with <%=raw tags.to_json
%>, then it returns this:
var tags_list = [
{"name":"tag1","color":"green"},
{"name":"</script><b>I can do something bad here</b>","color":"red"}
];
which, of course, breaks the HTML document with </script>.
Can I somehow tell to_json() method to return something more like this:
var tags_list = [
{"name":"tag1","color":"green"},
{"name":"</script><b>I can do something bad here</b>","color":"red"}
];
I asked this question on rubyonrails-talk mailing list, and I understand now that some people think that's a very bad idea to begin with, but in my case it works very nicely, as long as there are no HTML special chars in the data. So I just want to make the string returned by to_json HTML safe and still have JavaScript parse it properly.
UPDATE:
Based on #coreyward comment, I did make it a JS string literal, and that seems to be working great now. Its not quite as elegant of a solution as I was hoping for, but its not too bad either. Here is the code that is working for me:
<% tags = [{name:"tag1", color:"green"}, {name:"</script><b>I can \n\ndo something bad here</b>", color:"red"}] %>
<script type="text/javascript" charset="utf-8">
//<![CDATA[
var tags_list = $.parseJSON('<%=j tags.to_json.html_safe %>');
// ]]>
</script>
which results in:
<script type="text/javascript" charset="utf-8">
//<![CDATA[
var tags_list = $.parseJSON('[{\"name\":\"tag1\",\"color\":\"green\"},{\"name\":\"<\/script><b>I can \\n\\ndo something bad here<\/b>\",\"color\":\"red\"}]');
// ]]>
</script>
Your code using just #tags.to_json works in rails3, if you enable it with:
ActiveSupport.escape_html_entities_in_json = true
Otherwise, your other option is this:
var tags_list = <%= raw #tags.to_json.gsub("</", "<\\/") %>;
This saves the client having to parse the whole thing through $
The proper way in 2019 is to wrap obj.to_json with json_escape function. json_escape is directly intended for escaping specific HTML symbols inside JSON strings. Example below from the documentation:
json = JSON.generate({ name: "</script><script>alert('PWNED!!!')</script>"})
# => "{\"name\":\"</script><script>alert('PWNED!!!')</script>\"}"
json_escape(json)
# => "{\"name\":\"\\u003C/script\\u003E\\u003Cscript\\u003Ealert('PWNED!!!')\\u003C/script\\u003E\"}"
JSON.parse(json) == JSON.parse(json_escape(json))
# => true
It seems this page appears on top of Google Search results, that's why I decided to provide a comment with an update :)
btw, this works but is not a good solution in my opinion:
<script type="text/javascript" charset="utf-8">
//<![CDATA[
var tags_list = <%=raw #tags.to_json.gsub('/', '\/') %>;
// ]]>
</script>
I think that if you try this it will work:
var tags_list = "<%== #tags.to_json.gsub('/', '\/') %>";
(Notice the double == and the " ")
For instance with this in app/layouts/application.html.slim:
javascript:
window.translations = #{raw t("js").to_json};
And this in the translations:
js:
name:
must_be_present: Must be present<script>alert(1)</script>
The result will be escaped:
<script>window.translations = {"name":{"must_be_present":"Must be present\u003cscript\u003ealert(1)\u003c/script\u003e"}};</script>

Resources