I have a JavaScript Function where I want to call a Razor C# Function in it, I know it’s easy in HTML but in JavaScript i’m getting many compilation errors I tried the <text> tag trick but nothing worked.
getHTML is My JavaScript Function and getPageSource is a C# function that returns a string:
<script language="javascript" type="text/javascript">
function getHTML() {
var html = "@getPageSource("http://www.google.com")" ;
alert(html);
}
</script>
where @getPageSource is defined above the html and is working well within the HTML code
Is there any way to assign some Razor Code to a JavaScript Variable ?
You can’t execute server side functions in client side. Razor is only used to give you the ability to have some logic while generating the HTML code to be returned, in the server.
If that is a C# function that returns a String, you should wrap it inside quotes or it won’t be interpreted as a Javascript string when the browser is parsing your response.
Remember that if your getPageSource(“http://www.google.com”) returns a string with quotes inside, the javascript will be inconsistent and unable to create your JS string. Imagine that your method returned
<div> ' hello ' </div>. That would end up like:See the problem?
See this to convert a HTML C# String into one that can be used as a JS String.
http://codeasp.net/blogs/raghav_khunger/microsoft-net/722/how-to-escape-single-quotes-in-c-so-that-the-string-can-be-used-in-javascript
You must replace every
'with\\'. Remember that your string will be completely passed to the HTML code. Imagine that your code was returning"It's blue". When wrote in the HTML it would end asvar str = 'It's blue'(notice that"s blue"will be considered outside the string and will give a parsing error by the browser).To write that in JS you needed something like
var str = 'It\'s blue'so the browser will know that quote is not an ending string quote but it’s contained in the string.To include the dash in C#, your returning string must be
"It\\'s blue"once the replace of'with\\'