Passing strings with Single Qoute from MVC Razor to JavaScript - javascript

This seems so simple it's embarrassing. However, the first question is when passing a value from the new ViewBag in MVC 3.0 (Razor) into a JavaScript block, is this the correct way to do it? And more importantly, where and how do you apply the proper string replacement code to prevent a single quote from becoming &#39 as in the resultant alert below?
Adding this into a single script block:
alert('#ViewBag.str') // "Hi, how's it going?"
Results in the following alert:

Razor will HTML encode everything, so to prevent the ' from being encoded to ', you can use
alert('#Html.Raw(ViewBag.str)');
However, now you've got an actual ' in the middle of your string which causes a javascript error. To get around this, you can either wrap the alert string in double quotes (instead of single quotes), or escape the ' character. So, in your controller you would have
ViewBag.str = "Hi, how\\'s it going?";

Another solution to use JSON string:
C#
ViewBag.str = "[{\"Text\":\"Hi, how's it going?\"}]";
Javascript
var j = #Html.Raw(ViewBag.str);
alert (j[0].Text);

Related

Passing a string value from c# file to js file

I am trying to pass a string value from c# file to js file.
If I try to pass an int value, then I can pass it, but I am unable to pass string value.
string value = "abc";
int a=5;
TableCell.Attributes.Add("onclick", "F1("+value +")"); //NOTHING HAPPENS
TableCell.Attributes.Add("onclick", "F1("+a +")"); //Works Perfectly
js file
function F1(value) {
alert(value);
}
Pass string value in quotes ''
Use
TableCell.Attributes.Add("onclick", "F1('"+value +"')");
^ ^
Otherwise it treated as variable. Currently you must be getting error in browser console.
Consider what your HTML will look like.
First version:
onclick="F1(abc)"
Second version:
onclick="F1(5)"
Clearly the second version is passing the value 5. The first version is passing the value of abc - whatever that is, within the context of the Javascript you're executing.
You could quote the string, making sure that you escape quotes etc - I'm assuming that in reality, your value is fetched dynamically from somewhere, and you might not have much control over the content. Hopefully there's something within whatever ASP.NET version you're using that will let you do that, such as HttpUtility.JavaScriptStringEncode.
For example, to get the string abc in your call, you want the attribute to be:
onclick="F1('abc')"
but if to get the string I don't know in your call, you want the attribute to be:
onclick="F1('I don\'t know')"
The key is to look at the generated HTML - pretend you're the browser, and look at the world from its perspective. Once you've worked out what HTML you want to generate, writing the code to do so is often relatively simple.
Try adding single-quotes around the value when building it in your C# string. In your first scenario, the Js is receiving:
F1(abc);
Which it reads as being the variable abc. Try adding single quotes (and it's probably best to use string.format, BTW):
TableCell.Attributes.Add("onclick", string.Format("F1('{0}')", value));
When you use the string, it would produce the JavaScript code F1(abc). That would interpret abc as a variable name, not a string literal.
Add apostrophes around the string to make it a string literal:
TableCell.Attributes.Add("onclick", "F1('" + value + "')");
If the string can contain apostrophes or backslashes, you would need to escape them:
TableCell.Attributes.Add("onclick", "F1('" + value.Replace("\\", "\\\\").Replace("'", "\\'") + "')");
This will take care of escaping any special characters (i.e. quotes, etc...)
TableCell.Attributes.Add("onclick", "F1('"+HttpUtility.JavaScriptStringEncode(value)+"')");
If you're passing a string through the argument, you need either " or ' characters to delimit it. Your variable name is translating to (adb) in the call. ("adb") or ('adb') would be the string value.
That's because it will print
F1(abc)
So it will look for a variable called abc.
You should use
TableCell.Attributes.Add("onclick", "F1(\""+value +"\")");
So the output will be
F1("abc")

Javascript with Special Chartecter

I have a html page in which I need to pass a String variable to javascript function. This works until String does not have a special charecter.
<html>
<head>
<script>
function test(v){
alert(v);
}
</script>
</head>
<body>
<input type="button" value="Test Button" onClick="test('BlahBlah')"/>
</body>
</html>
As soon as I change onClick like below, it stops working.
onClick="test('Blah'Blah')"
Any solution for this problem. Please take a note parameter which is being passed to JavaScript function is dynamic.Source of Parameter is backend and I cannot change that peice of code. Second thing even if put escape it still does not work. My problem is I have to retian the special charecter for some processing at backend
There are two layers to this:
The content of onClick attributes, like all attributes, is HTML text. That means that any character that's special in HTML (like <) must be replaced with an HTML entity (e.g., <). Additionally, if you use double quotes around the attribute value, any double quotes within the value must be replaced with entities ("); if you used single quotes around the attribute, you'd need to replace ' with &apos;.
Your attribute contains a JavaScript string literal. That means that any characters that are special inside JavaScript string literals must be escaped according to the JavaScript rules. Since you've used single quotes to delimit the JavaScript string, for instance, you have to escape any single quotes in the string with a backslash.
I'm assuming that HTML is generated server-side. If so, the work above must be done server-side, when building the HTML of the page. You haven't said what server-side tech you're using, so it's hard to point you at solutions that your server-side tech/environment might provide.
In the simple case of your
onClick="test('Blah'Blah')"
...you just need to add the backslash within the JavaScript string
onClick="test('Blah\'Blah')"
...but that's just that one specific case.
The dramatically simpler option is to not put JavaScript code in attribute values. Instead, use modern techniques (addEventListener, attachEvent) to hook up JavaScript code.
But if you must use an onClick attribute, avoid having text in it (or deal with the complexities above); have it call a function defined in a script element that then has the text, as you then have only the one layer (#2 above) to deal with.
Source of Parameter is backend and I cannot change that peice of code.
That backend is broken and needs fixing.
If:
the backend is only producing invalid JavaScript code (not invalid HTML)
and the code consists of a single function call
and the code is always a single function call
and the function call always has a single string literal argument
and that argument is always delimited with single quotes
and the single quotes within the string are never correctly escaped
...we might be able to salvage it client-side. But my guess is that the backend will also produce invalid HTML, for instance when the text has a " in it. (We can't do anything about that, because the attribute value will be chopped off at that point.)
But let's keep a good thought: Given the ridiculous list of caveats above, this might do it:
var elm = document.getElementById("the-div");
var code = elm.getAttribute("onclick");
var m = code.match(/^([^(]+)\('(.*)'\)$/);
if (m) {
code = m[1] + "('" + m[2].replace(/'/g, "\\'") + "')";
}
elm.setAttribute("onclick", code);
Live Example:
function foo(str) {
alert(str);
}
var elm = document.getElementById("the-div");
var code = elm.getAttribute("onclick");
var m = code.match(/^([^(]+)\('(.*)'\)$/);
if (m) {
code = m[1] + "('" + m[2].replace(/'/g, "\\'") + "')";
}
elm.setAttribute("onclick", code);
<div id="the-div" onclick="foo('blah'blah')">Click me</div>
Well this is an very common problem you wanted to add single quotes inside single quotes to do this you have to escape that Sigle quotes to do that you have to put an forward slash.
onClick="test('Blah\'Blah')"

Store Html.Raw() in a string in Javascript, ASP.NET MVC 3

I'm using ASP.NET and I have a string of HTML in the database.
I want to get that html into a variable on the client.
If I do this:
var x = '#Html.Raw(myModel.FishValue)'
it works fine, because it's essentially doing
var x = '<p>hello!</p>';
however if there are quotes in the html it breaks the page.
My initial guess would be to .Replace the raw string to add escapes to the quotes, however both .ToString() and .ToHtmlString() (as Html.Raw returns an IHtmlString) do not produce the same markup as simple Html.Raw().
So I'm at a loss of what best to do.
What about replacing before calling the Html.Rawmethod?
var x = '#Html.Raw(myModel.FishValue.Replace("'","\\'"))'
UPDATE:
There might be other escape chars in the string coming from the model. For that reason I would recommend replacing the slashes first as well. Of course it all depends on what might come from the server in your model.
var x = '#Html.Raw(myModel.FishValue.Replace("\\","\\\\'").Replace("'","\\'"))'
A sample snippet representing the behavior in the javascript:
//Let's say my Model Content is > I'd Say \ is a escape character. You can't "Escape"
// YOu would have to replace ' --> \' and \ --> \\
var stringFromServer = 'I\'d Say \\ is a escape character. You can\'t "Escape"'
alert(stringFromServer)
Try this:
var x = '#(System.Web.HttpUtility.HtmlEncode(myModel.FishValue))';
If you need to decode the HTML on the client side use
unescape(x)
I think JQuery (not sure if you're using it or not) handles encoded HTML strings so you might not need unescape().
Try out the anti-xss library from Microsoft (which will be included I believe by default in asp.net 4.5):
AntiXss.JavascriptEncode(yourContent)
Anti-Xss is available 4.1 beta. If you want to use it in your application which I highly recommend, check out:
http://weblogs.asp.net/jgalloway/archive/2011/04/28/using-antixss-4-1-beta-as-the-default-encoder-in-asp-net.aspx

How to deal with sigle quote in javascript in jsp page?

onclick= "_deleteWPSchemeData(${viewWPMasterGrid.id}, '${viewWPMasterGrid.name}')"
${viewWPMasterGrid.name} retutrns me a string(for e.g. W.P.WINT OFF ALL'10) which often has single quote character so from the calling javascript method I am not getting the second parameter at all. How to deal with problem?
When a dynamic String can be put inside a JavaScript string literal, it should be JS-escaped. Just as when a dynamic String is put inside a HTML page, it's HTML-escaped.
Use commons-lang StringEscapeUtils.escapeECMAScript (or escapeJavaScript depending on the version) to escape the String. You could create a very simple EL function to do that straight from the JSP.
Note that you could have problems with single quotes, but also double quotes, tags, EOLs, backslash, which must all be escaped in a JS String literal.
It looks like you could split the second parameter out into its own variable first. If I have understood your question correctly.
var viewWPMasterGridName = "${viewWPMasterGrid.name}";
onclick = "_deleteWPSchemeData(${viewWPMasterGrid.id},'" + viewWPMasterGridName + "')";
Use '${viewWPMasterGrid.name.replaceAll("'", "\'")}'
try this,
var name = "${viewWPMasterGrid.name}".replace(/'/g,"\\'");

Error using Javascript and JSP, string with space gives `Unterminated string literal`

I have to pass a string value to JavaScript from JSP page.
I am using
display("<%=name%>")
It works fine but when i have string like 'sweet milk', JavaScript throws the error
Unterminated string literal
How to solve this?
Your string contains single quotes - you can escape single quotes as "\x27" and double quotes as "\x22" and then pass it to javascript.
You probably have characters in your String that should be escaped in Javascript. For example, if your string is My name is "John", your code will generate
var a = "My name is "John"";
which is invalid.
You should use StringEscapeUtils.escapeJavaScript from commons-lang to make sure everything is correctly escaped (single and double quotes, newlines, tabs, etc.).
I guess there's an error in the generated JavaScript code. Is there any way to look at you page? I suggest to look at the generated source code of that page.

Categories

Resources