How to fix this "syntax error" in Razor? - c#

I have code like this in my Razor view
<script>
var JsModel = #Html.Raw(Json.Encode(CsModel));
</script>
This works just fine. It converts the C# model received from the controller to a JS object, which is later used to populate Google Map with markers and various other stuff.
The problem is, Visual Studio is showing a big red syntax error in this line, and it's driving me insane. The code is perfectly fine, model is always non-null, and the encoding always works. But Razor parser, or perhaps even R#, I'm not sure which, trips up on it, as it seems to ignore C# code. So what it sees is just var JsModel = ; and complains.
Any way for me to tell it that it's ok? What can I do here?

We can get around this by putting raw json into quotes, and thus tricking the parser, and then using JQuery eval (or any other eval you prefer) to convert string into an object.
<script>
var JsModel = $.parseJSON('#Html.Raw(Json.Encode(CsModel))');
</script>

<script>
var JsModel = '#Html.Raw(Json.Encode(CsModel))'; //apply single quotes as shown
</script>

Use function as shown below :
function SetMyValue(value){
return value;
}
var JsModel = SetMyValue(#Html.Raw(Json.Encode(CsModel)));
As documented here http://msdn.microsoft.com/en-us/library/gg480740(v=vs.118).aspx:-
This method wraps HTML markup using the IHtmlString class, which
renders unencoded HTML.
The Razor escaping system will not escape anything of type IHtmlString. The Html.Raw() method simply returns an HtmlString instance containing your text.
So wrapping it into function and returning from there would work for you.

Related

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

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'.

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.)

Call JS function from CodeBehind file

I am having trouble accessing a Javascript function from my code behind file. I need to do this as I am using the GoogleMaps JS API to add markers to a map based on addresses retrieved from my database. I have a function called AddMarker that takes in the address as a parameter, so I need to be able to call that from my code behind file in the page_load function.
To simplify the question, how I can I call this javascript function to display an alert with a string passed from my code behind file?:
function hello(message)
{
alert(message)
}
Thanks in advance!
P.S Either vb or c# will do :)
You may consider this a hack but you could always put your message in an html element like:
<p id='message' style='display: none;'>Your Message</p>
Then in your javascript:
function hello()
{
var m = document.getElementById('message').innerHTML;
alert(m);
}
That should do:
protected void Page_Load(object sender, EventArgs e)
{
string bing = "link";
Response.Write(#"<script language='javascript'>alert(bing);</script>");
}
I'm not certain if this is best practice, but you could just render out a call to the JS function somewhere in your page, after it has been defined.
Or you could use jQuery to delay the call until everything in the page is rendered.
So
<script type="text/javascript">
$(document).ready(function(){
hello("myAspString");
});
</script>
Replace myAspString with your content, making sure to preserve the quotes as needed by JS.
This code will cause the function hello to be called with value from the code behind:
string value = "world";
Page.ClientScript.RegisterClientScriptBlock(this.Page.GetType(), "my_script", string.Format("hello('{0}');", value.Replace("'", "\\'")), true);
The RegisterClientScriptBlock will append proper <script> tags to the HTML output sent to browser and inject your code in there.
The second argument is the "key" of the script, it enable you to have several statements and check if you already registered specific statement based on the key. The last argument tells the framework to add <script> tags for you.
You need to replace any single quotes with the proper escape sequence to avoid breaking the string when it contains single quotes as this is the "delimeter" used to pass the value to the function.

C# Deserialize JSON html string

I'm trying to deserialize a JSON object in c#, my problem is that one of the fields can contain html text (I plan on sanitizing it afterwards).
I’m using a JavaScriptSerializer object to deserialize, but I’m getting a “Invalid object passed in“ error (from the JavaScriptSerializer). If I pass plain text for that same field it works fine and the other fields (including a date and an array) in the object also deserialize correctly so it seems like the html is what’s tripping it up.
I’m using JSON.stringify to serialize the Javascript object and I’m passing it to my page via jQuery.
Is there something I’m supposed to do to in order to pass a string that contains html? I’ve tried enclosing it in quotes, but it didn’t help.
As an example of a string that's accepted vs what throws an error: "Test" is fine while
"<div style="text-align: center;">Test</div>" is not.
Strangely <span> tags also seem to be fine.
Can you encode the html with the javascript escape() function before serializing.
You may have to encodeURIComponent in javascript, then HttpServerUtility.UrlDecode in .NET
You can't pass in HTML characters that aren't encoded for security reasons. You can override this in MVC.Net at the application of function level if you feel secure in your source.
just do some replace like this
jsonString.Replace(#"=""\""",#"=\""\""").Replace(#"\""""",#"\""\""").Replace(#"=""""", #"=\""\""")

Protect against script injection using markdown

I want to protect my page when a user inputs the following:
<script type="text/javascript">
alert("hi");
</script>
I'm using ShowDown:
jQuery.fn.markDown = function()
{
return this.each(function() {
var caller = this;
var converter = new Showdown.converter();
var text = $(caller).text();
var html = converter.makeHtml(text);
$(caller).html(html);
});
}
If you want to sanitize html on a .NET server-side code, I'd advise you use Microsoft web protection library, after transforming the markup to html, before rendering it to the page.
e.g. the following snippet:
x = #"<div>safe</div>
<script type='text/javascript'>
alert('hi');
</script>";
return Microsoft.Security.Application.Sanitizer.GetSafeHtmlFragment(x);
returns <div>safe</div>
http://wpl.codeplex.com/
One of the solution that could be effective would be to strip all the tag in the source or HTML encode the tag before it is transformed with Showdown.
For how to strip all the HTML tag, there are a couple of way to do it that you can find in this question :
Strip HTML from Text JavaScript
For how to HTML encode the tag, you can use this :
myString.replace(/</g, '<').replace(/>/g, '>');
Note: This will remove you the ability to use HTML in Showdown.
The ShowDown page strips any javascript, so I don't know what you mean exactly. But you can't do this on the client. If this is never going to be submitted to the server, then it doesn't matter. However, 99% of the time, you want to store it on the server.
I think the best approach is to create a server side DOM object out of the html that is submitted (which could be spoofed and bypass ShowDown) and look for any script or other dangerous tags. This is not so simple!
The best compromise for me is to use a server side markdown language (like https://github.com/charliesome/bbsharp) that you could then use to generate the html. You would then html encode any html before passing it to the tool that converts the markdown to HTML.
I use HTML Purifier which works very well for filtering user input and is highly customizable.
I assume you can use it with MarkDown, although I never tried.

Categories

Resources