javascript alert not working - c#

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

Related

calling two javascript function in href for a tag

I am trying to do this :
<a id="seeAll" onclick="stopClickEffect(event)" href='
<%#
String.Format("javascript:PositionPopup("#MapPos", this);ShowMap(\"{0}\",\"{1}\",\"{2}\");",
Eval("LONGTITUDE").ToString(),Eval("LATITUDE").ToString(),Eval("CASA_NAME").ToString())
%>'
class="see_all colored_font">[Show map]</a>
But I get the error Preprocessor directives must appear as the first non-whitespace character on a line
How do I fix this?
The # in front of your String.Format tells the C# preprocessor that this is a preprocessor-directive, like #region asdf and #endregion.
Because you marked the line with the # it is interpreted as such a directive. And because of the whitespace after the # you get this error message.
To be clean, remove the # from the href, and you should be fine.
First of all, you should NOT place Javascript code in the href attribute. Only use the onclick handler. From HTML/Javascript point of view, it is no problem to put more than one function there:
...
The error comes from c# code, I guess you have to escape the # and " in your code. String.Format escaping is described here. You use double curly brackets like this: "{{...}}"
I'm not sure what the stopClickEffect function does, but maybe you can even leave that out when you return false in the end of the onclick handler.
it should have been like this
<a href = 'http://localhost/abc/' onclick = 'return test()' >
And javascript function
function test(){
//you code
return false // this will not allow href to go to another page
return true // let href go to another page
}
If I'm not mistaken, you should be able to place the code in your href attribute in a separate JS function, which you can define outside of that tag. You could then just call that function from the tag, instead of placing all the code there.
That should make it easier for you to fix the problem, and make your code more readable too.
I don't believe JavaScript or HTML have preprocessor directives; however, c# does.
If you are doing something related to c# I'd imagine that the code that is giving you the error is not on the line you linked. A preprocessor directive starts with # and is usually towards the top of your c# code.
The error is saying that you cannot have anything before the # on the line you are using a preprocessor directive. If this line is the line causing issues, it's probably the "<%# string" part. Remove that hash tag and try again.

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

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 "render" HTML without WebBrowser control

First at all - I don't know if "render" is the right word. I like to get information from an website. At the moment therefore I use the WebBbrowser control.
Now I like to use HttpWebRequests because I think, that's much faster and threading could be used more easily. But I can't use them, because the HTML-output string I receive from HttpWebRequest has got a lot of JavaScript inside from which the information, that I need, will be created.
The web browser "renders" the JavaScript to readable HTML. How to do this step "by hand", so that I can use HttpWebRequests?
I hope you understand, what I want.
so if you need the javascript rendering engine i suggest you have a look at selenium project.
I solved my problem with a project called Awesomium. In this thread you will find all you need to get html with executed javascript. The "special part" is this one:
var sourceVal = webView.ExecuteJavascriptWithResult( "document.getElementsByTagName('html')[0].outerHTML;" );
if ( sourceVal != null )
{
using ( sourceVal )
{
html = sourceVal.ToString();
}
}

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