Javascript / ASP.NET MVC 4 - Using C# Strings in Javascript - c#

I need to be able to access strings held in my C# code in JavaScript. To test, I have tried displaying a message box with the C# string in JavaScript (I am using this string literal and the message box as an example scenario):
alert(<%: "TEST" %>);
When this code runs, no message box is displayed. On the other hand, a message box is displayed with this code:
alert(<%: 6 %>);
Why is it that I can use integers but not strings? Is there any way around this?
Thanks.

You need to add quotes around the string; otherwise, the browser sees alert(TEST);, which is incorrect. To prevent cross-site scripting attacks, you also need to properly escape special characters. Calling HttpUtility.JavaScriptStringEncode lets you do both:
alert(<%= HttpUtility.JavaScriptStringEncode("TEST", true) %>);
Note: If this JavaScript snippet appears inside an HTML attribute like onclick, you may need to change <%= to <%: so that the double quotes are also HTML encoded.

Why is it that I can use integers but not strings?
Because you need to put strings in quotes:
alert("<%: "TEST" %>");
The key here, as always, is to look at what the browser actually receives. With your original code, what the browser sees is:
alert(TEST);
...which is trying to use the variable TEST, not a literal string.
Now in the above, I've assumed the string won't have any " in it or other things that aren't valid within a JavaScript string literal. That's not usually a good assumption to make.
If you're using a recent version of .Net or using JSON.Net (see this question for details), you can output the string using a JSON serializer, which will ensure that anything within it that may be problematic is properly encoded/escaped. For instance, with JSON.Net, you might use:
// With JSON.Net
alert(<%: JsonConvert.ToString("TEST") %>);
// With a recent version of .Net
alert(<%: HttpUtility.JavaScriptStringEncode("TEST", true) %>);

The problem is in how this translates into JavaScript:
alert(<%: "TEST" %>);
becomes
alert(TEST);
This is a problem because it assumes there is a variable named TEST that you'd like to display the value of, but most likely, TEST is undefined. What you probably want to do is this:
alert('<%: "TEST" %>');
But since this is MVC 4, you can use the Json.Encode method to be a little cleaner, like this:
alert(<%: Json.Encode("TEST") %>);
Both of thse will translate to
alert('TEST');
This should display a message box with the string 'TEST'.

Related

Why root symbol does not works in hyper link when returned by an expression?

Just a thought came in mind.
Why the first of these two tags does not work in asp.net?
To me both are string values whose final value is same. Which is value of attribute href of hyperlink.
Please make me understand it.
Test
Test
Note: I am not looking for solution to it. Only want to understand what's logically difference between these two case.
To me both are string values whose final value is same
Not really. Consider first if you just had a plain non-razor HTML form such as if you'd hard-coded the beginning of the path:
Test
Now, here "/SomeProject/Test/Index" is not a string. It's an attribute value in HTML. HTML has no concept of "string". Sure it happens to use the same delimiter as C# does for string, but this isn't C# here.
With Razor we have a few means to indicate we want something done by Razor to the otherwise plain HTML.
# is one of them, indicating that we want a C# expression evaluated and the result (if not void) output. And the result of (string.Format("~/Test/Index")) is ~/Test/Index so that is output.
~/ is, in certain contexts, another one, indicating that it should be replaced with the value of evaluating Href("~/") or Url.Content("~/"), which would be something like / or /SomeProject/ or whatever. It's not so much a string as something more like a keyword.
If you have an expression returning a string, you can still use strings similarly with:
Test
Which incidentally, was the only way this could be done in Razor 1.0. The direct parsing of "~/… was added as a convenience and it is indeed convenient.
I think you're misunderstanding what string.Format(string format, params Object[] args) does. It will only replace specified placeholders {0}, {1}, etc with provided paramters. Take a look at the docs in the link provided for more info.
In short it doesn't do any automatic replacement of environment variables or any other substitutions not already covered by the placeholders.
String.Format sits in the System namespace, therefore I wouldn't expect it to know anything about web sites, file systems or anything more complicated than simple placeholder substitution and formatting.
You should be using Url.Action i.e.
Test
or even easier
#Html.ActionLink("Test", "Index", "Test")
Also note that in ASP.Net MVC you don't use the full controller name, only the prefix i.e. Test instead of TestController

Is it possible to change the way Attribute.Add formats the addition of the attribute?

My Question: Is it possible to change the way Attribute.Add formats the addition of the attribute?
I have an ASP.net website that loads a widget in a div, and I'm trying to find a way to add a data-options attribute to the div with my codebehind. I need the attribute to be created with a single quote around the data-options value instead of double quotes, because the value I'm assigning is a JSON pair.
What I need the attribute to look like:
data-options='{“post_message_origin”:”https://www.mysite.com/MyWidget.aspx”}'
What it looks like when using Attribute.Add("data-options"):
My code:
string dataoptions = "{\"post_message_origin\":\""+ HttpContext.Current.Request.Url.AbsoluteUri + "\"}";
MYWIDGET.Attributes.Add("data-options", dataoptions);
The attribute result:
data-options="{“post_message_origin”:”https://www.mysite.com/MyWidget.aspx”}"
The set of double quotes encompassing the data-options value is preventing the JSON pair from being read correctly, hence my question.
I'm doing my best to avoid using hard coding so that I can easily load the page from development servers to production servers without changing the code, which is why I'm using HttpContext.Current.Request.Url.AbsoluteUri in the code behind instead of writing the data-options value straight to the div in the ASP markup.
I would suggest using single quotes with the JSON, in this case. Either is acceptable, as long as they are in open-close pairs. This sidesteps the issue.
EDIT: Unfortunately, Attribute.Add encodes the quotes...
This has been brought up before. It looks like the long term solution is implementing your own encoder...
I would recommend including neither kind of quote in your data:
string dataoptions = "{\"post_message_origin\":\""+
HttpContext.Current.Request.Url.AbsoluteUri + "\"}";
dataoptions = dataoptions.Replace("\"", """).Replace("'", "&apos;");
MYWIDGET.Attributes.Add("data-options", dataoptions);

What is the dollar symbol used for in ASP.net?

I know this might be a newbie question, but every-time i see code like this:
var table = $("table[title='Refresh']");
And also code like this:
$(function () {
$("#datepicker").datepicker();
});
i always sort of glaze over the $ symbol . It's a type of placeholder? or does it signify that its dynamic?
It is a JavaScript function, most likely jQuery. Many JS frameworks define $ as a root selector function, jQuery being the most famous/used of those.
It has nothing to do with ASP.NET.
The $ is not related to ASP.NET in particular, but rather to the possible use of jQuery or Prototype which both use the $ as an alias for a function. In the case of jQuery, $ is just a shortcut for not having to write jQuery as in the following example:
jQuery('selector').datepicker()
Is the same as writing
$('selector').datepicker()
jQuery provides the noConflict() method precisely to avoid conflicts with any other Javascript framework that may use the same $ alias.
This isn't part of ASP.NET, it's actually part of the JQuery library, which is a JavaScript library used for client side processing.
http://jquery.com/
It's the Shortcut / Alias to use in jQuery. Can be replaced with "jQuery " keyword."
This is jquery syntax of using $ symbol. Read more here http://www.learningjquery.com/2006/09/introducing-document-ready
That is JavaScript code. In JavaScript, $ is a legal name for a function or variable. It just means that someone defined a function with that name. You could define one yourself simply enough:
function $(){return "hello world";}
Then $() would print "hello world".
Most famously, JQuery uses it as their selector function, in which it is used to query the page's DOM in a more powerful syntax than JavaScript's built in DOM querying methods, but there's nothing that guarantees that $ is JQuery's usage, it could be anything. (Note that I highly discourage you from actually defining $ yourself and using it as a function, as virtually all JS developers have learned to read it as the JQuery's implementation.)

How can i add double quotes to a string?

I want to add double quotes for a sting . I know by using /" we can add double quotes . My string is
string scrip = "$(function () {$(\"[src='" + names[i, 0] + "']\"" + ").pinit();});";
When i do this on the browser i am getting &quot instead of " quotes . How can i overcome with the problem ?
If your browser has displayed a "&quot" instead of a " character, than there are only a few causes possible. The character should have been emitted to the browser as either itself, or as a HTML entity of ". Please note the semicolor at the end. If a browser sees such 'code', it presents a quote. This is to allow writing the HTML easier, when its attribtues need to contain special characters, compare:
<div attribute="blahblahblah" />
if you want to put a " into the blahs, it'd terminate the attribute's notation, and the HTML code would break. So, adding a single " character should look like:
<div attribute="blah&quote;blahblah" />
Now, if you miss the semicolon, the browser will display blah&quotblahblah instead of blah"blahblah.
I've just noted that your code is actually glueing up the JavaScript code. In JavaScript, the semicolon is an expression delimiter, so probably there is actually a " in the emitted HTML and it is just improperly presented in the error message... Or maybe you have forgotten to open/close some quotes in the javascript, and the semicolon is actually treated as expression terminator?
Be also sure to check why the JavaScript code undergoes html-entity translation. Usually, blocks are not reparsed. Are you setting that JavaScript code as a HTML element attribute? like OnClick or OnSend? Then stop doing it now. Create a javascript-function with this code and call that function from the click/send instead.. It is not worth to encode long expressions in the JS into an attribute! Just a waste of time and nerves.
If all else fails and if the JavaScript is emitted correctly, then look for any text-correcting or text-highlighting or text-formatting modules you have on your site. Quite probable that one of them is mis-reading the html entities and removed the semicolon, or the opposite - that they add them were they are not needed. The ASP.Net itself in general does its job right, and it translates the entites correctly wherever they are needed, so I'd look at the other libraries first.
You can use something like this:
String str=#"hello,,?!"
This should escape all characters
Or
String TestString = "This is a <Test String>.";
String EncodedString = Server.HtmlEncode(TestString);
Here's the manual: http://msdn.microsoft.com/en-us/library/w3te6wfz.aspx
What else are you doing with the string?
Seems that somewhere after that the string gets encoded. You can could use HttpUtility.HtmlDecode(str); but first you'll have to figure out where your string gets encoded in the first place.
Keep in mind that if you use <%: %> in aspx or #yourvarin Razor it will get encoded automatically. You'll have to use #Html.Raw(yourvar) to suppress that.

How to display correctly this string on an alert javascript

I have this string :
myString="Città"
and I'd like to display correctly (as Città) on an alert in Javascript. How can I do it from C# using Javascript/jQuery?
Here for the example
I think you don't need to use that notation in javascript. If you run alert('Città') the browser will show it correctly.
You need to use the Unicode character. This example uses the escaped form.
alert("Citt\u00e0");
This worked fine for me.
EDIT: see this page for reference (scroll down to "Encodings")
EDIT THE SECOND:
You might need to do a string replace on your returned value from the database.
var myString = "Città";
alert(myString.replace("à","\u00e0"));

Categories

Resources