Call JS function from CodeBehind file - c#

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.

Related

How to fix this "syntax error" in Razor?

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.

ScriptManager - RegisterStartupScript ( with 2 parameters)

I learn ASP.net and C#,
I want to call a JS function , from C#.
This is the function in JS:
<script type="text/javascript">
function open(x,y)
{
alert(x);
}
</script>
and this is the line from C# (when Allcc is a string):
ScriptManager.RegisterStartupScript(this, typeof(string), "Pop", String.Format("openModal('{0}{1}{2}');",0,",", Allcc), true);
I have to transfer 2 parameters(1- number 0 . 2- Allacc (string)), but actually I get only one string . what Should I change to send both of the parameters separately?
Thanks!
You are enclosing all the values in one pair of single quotes. The current call would be like "openModal('0,valueOfAllcc');" To pass two parameters you need to use two pairs of single quotes
String.Format("openModal('{0}'{1}'{2}');",0,",", Allcc)
I think you have openModal instead of open in javascript as you are calling openModal.

javascript alert not working

I have this code and I am trying to run it on a .NET platform but it is not working. Does anyone have any idea what is wrong with my code? Thanks. I am using visual studio 2010, and c# programming language.
private void AlertWithConfirmation()
{
Response.Write("<script language='javascript'>");
Response.Write("var x=window.confirm(\"Are you sure you are ok?\")");
Response.Write("if (x)");
Response.Write("window.alert(\"Good!\")");
Response.Write("else");
Response.Write("window.alert(\"Too bad\")");
Response.Write("</script>");
}
Your code produces this:
<script language='javascript'>var x=window.confirm("Are you sure you are ok?")if (x)window.alert("Good!")elsewindow.alert("Too bad")</script>
Note the elsewindow identifier that comes from the lack of separator between the commands, which of course does not exist. It will cause an error because the undefined value doesn't have an alert method.
Some improvements:
Use the type attribute instead of the deprecated langauge attribute.
Use semicolons at the end of statements.
Use brackets around code blocks (e.g. following if).
Use the return value from confirm directly instead of polluting the global namespace with a variable.
Write it as a single string instead of a bunch of strings.
:
private void AlertWithConfirmation() {
Response.Write(
"<script type=\"text/javascript\">" +
"if (window.confirm('Are you sure you are ok?')) {" +
"window.alert('Good!');" +
"} else {" +
"window.alert('Too bad');" +
"}" +
"</script>"
);
}
Note that if you use this within a regular page, it will write the script tag before the doctype tag, which will cause the browser to go into quirks mode, which will most likely mess up your layout. If you want to add scripts to a regular page you should put a PlaceHolder on the page where you can add it, or use the ClientScriptManager.RegisterStartupScript method.
Make sure the result of the Response.Write looks something like this:
<script type="text/javascript">
var x=window.confirm('Are you sure you are ok?');
if (x) {
window.alert('Good!');
} else {
window.alert('Too bad');
}
</script>
The HTML generated by an aspx page is rendered in the Render phase which is at the end of the page lifecycle.
Therefore if you call Response.Write earlier in the page lifecycle, it will output at the start of the page before the first tag - almost certainly not what you want.
If you inspect the generated HTML (View Source in the browser) you'll see this.
In general, if you want to render some javascript you should use some other technique, such as setting the Text property of a Literal control at the appropriate place in the page.
You have already asked two similar questions in a period of 24h. You got to have some patience.
how to use javascript alert so that user can choose
Javascript alert problem

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.

Regex for getting javascript functions in C#.net

I use webBrowser.DocumentText to get the html code of a page.
using Regex, i manage to get the script tag part.
< script type="text/javascript">functions here..< /script>
I need to get functions inside those tags.
ex.
<script type="text/javascript">
function function1 () { code here;}
function function2 () { code here;}
<br>
</script>
I need regex pattern to get the 2 functions or list them down like this
1. function funtion1() { code here; }
2. function funtion2() { code here; }
purpose of the program is to identify if there's a duplicate javascript functions between
2 pages.
Its for winForms and language is C#
You can not do it in any general way with regexes alone (especially not with the .NET flavour), since JavaScript scopes can be nested arbitrarily deeply and the language is therefore irregular. If you need them for a few particular pages, you might be able to craft a regex that handles common cases, but not all.
e = ".*?(function.+?{.*?}|\\z)";
repl = "\\1";
I believe that's it.

Categories

Resources