ASP.NET Server-Side Comments inside <script> Block - asp.net

I know that you can create 'server-side comments' (they won't be sent as comments/text to the client) in ASP.NET (MVC) via the <%-- Comment --%> tags.
However, I can't seem to do this inside of a <script> tag -- if I try this I get a bunch of code underlined in red, and weird unrelated errors ("Invalid expression term '}') etc. from Visual Studio.
Is there another way to have server-side comments inside of the script tag? I want to comment my inline Javascript, but don't want my comments sent to the client.

You can add the comment no problem.
Visual Studio is stupid and doesn't recognize the ASP <%-- Comment %> tags in JS. Your page will still compile fine.
As mentioned in another answer, using //<%-- Comment %> will hide your comments (but leave the //).
Also, be careful of ASP.NET's habit of ignoring whitespace or line breaks around ASP-wrapped code:
//<%-- Comment %>
var whatever = '';
May become:
//var whatever = '';
at run time.

Have you tried commenting the lines with javascript comments as well? Apparently this should work:
<script type="text/javascript">
<%--
// Comments that
// will not be rendered
//--%>
</script>
Taken from a post on Scott Guthrie's blog here.

You can add comments in javascript by making each line start with "//". Those survive through the ASP.NET engine just fine.

Server tags does work inside aspx javascript tags.
But visualstudio doesn't get it, it gives you lots of errors, but if you run the page it will work.
Its the same if you do serverside inside a html tag.

Shouldn't you ideally be decoupling your JS code from ASPX as much as possible? The bulk of your JS code that is complicated enough to deserve commenting should reside in stand-alone JS files. You should have the bare minimum amount of code on the ASPX side and simply invoke JS functions etc. from the external JS files.

Related

jQuery undefined in content page when using master pages which has jQuery reference

I have a nested master page. A parent master page, a child master page and a content page whose master page is the child master page. I have a reference to jQuery in the parent master page in the head section.<script type="text/javascript" src='<%#ResolveUrl("~/includes/jquery-1.4.2.min.js") %>' ></script> & Page.Header.DataBind(); in the OnLoad event.
I am using jQuery in all the pages including the master pages. However I am getting "Error: $().ready is not a function" in the content page. If I include jQuery reference in the content page it works.
Question: If the reference to jQuery is in the master page head section, why aren't the content pages able to use jQuery? When I do view source, the script tag with jQuery is there and it works.
The master pages and content page are merged during rendering and sent to the browser as a single html page so I am not sure when master pages are used, jQuery references break.
UPDATE:
When I changed '$.ready(function()' to 'jQuery(document).ready(function($)' it worked! I am not loading any other javascript libraries and I am not using MS Ajax.
First, and I didn't notice this before, but is your original call to $.ready(function() {}), which didn't work, but jQuery(document).ready(function() {}) did work? Does your call work if you use $(document).ready(function () {} )? Just wanted to make sure it's not a typo. The jQuery docs say the $.ready(function() {}) is valid, but it's not recommended.
OK, assuming it's not a typo, it definitely sounds like you have a conflict with the '$' variable. If you're using third-party controls or ASP.NET AJAX, you may run into conflicts (even though you may not be including the JS file explicitly).
If you could post what gets output by the browser after your page loads, that would help.
Also, if you run Fiddler (or some other traffic request tool), you can see if any JS references are being downloaded. Look not only for .JS files, but also .AXD files (some third-party tools name these files ScriptResource.axd or WebResource.axd, and they may redefine the '$' variable).
You may want to check out this link on the jQuery API page about the noConflict function. This helps when you have a conflict with the $ variable.
Without seeing the output, it's tough to diagnose. But hopefully this helps.
i also have the same issue, it sounds like a jQuery conflict
i fixed my issue :
<script type="text/javascript" >
$(document).ready(function () {
$.noConflict();
});
</script>
in the <head> section

Visual Studio confused by server code inside javascript

I ran into an annoying problem: the following code gives a warning in Visual Studio.
<script type="text/javascript">
var x = <%: ViewData["param"] %>;
</script>
The warning is "Expected expression". Visual Studio gets confused, and all the javascript code after that is giving tons of warnings. Granted, it's all warnings, and it works perfectly fine in runtime - but it is very easy to miss real warnings among dozen of false positives.
It was working the same way in VS2008, and it wasn't fixed in VS2010. Does anybody know if there is a workaround, or a patch?
You need to wrap the server side expression in quotes.
<script type="text/javascript">
var x = "<%: ViewData["param"] %>";
</script>
This is what I got from Microsoft:
Unfortunately, this is due to a design limitation of our editor. We have had multiple users provide the same feedback, but we do not have a good solution at this time, other than to avoid server-side generation of client script. We will consider this issue in our planning for the next Visual Studio release.
You can trick the IDE using quotes or line comments
original code:
<script type="Text/javascript">
<%If Page.IsPostback Then%>
alert("my javascript code");
<%End If%>
</script>
solution:
<script type="Text/javascript">
//<%If Page.IsPostback Then%>
alert("my javascript code");
//<%End If%>
</script>
The approach you're taking is not a particularly sturdy one. Obviously it wouldn't work if you wanted to move your Javascript code to a separate file in order to improve your page load times....
You're better off using hidden form fields to move data from the server to client script. Alternatively, you can build the variable setter JS code programmatically by doing a bunch of string concatenation, then using the ClientScriptManager.RegisterClientScriptBlock() method to inject it into the output.
I believe that you ask from visual studio to understand too difficult thinks.
How visual studio can know what is inside the string that you pass ?, its parameters, its more code, what it is ???.... How VS can know what it is so can tread them that way ?
So they decide that everything on script tag there must be JavaScript.
My opinion is that if you won to avoid this error, Write render this JavaScript on code behind and not inside aspx page.
string cPlaceMeOnScript = "<script type=\"text/javascript\">var x =" + ViewData["param"] +";</script>"
and use any method to place this string on the start of your script.
I can't believe how many responses say "Put the JavaScript in the code-behind instead". This is a very bad idea, and muddles your code by mixing presentation with business logic. As the original poster stated, this is only a mere warning. While annoying, it's not worth mixing your presenatational behavior in with your server-side code (a.k.a. writing poor code) over.
This is not the standard behavior, and it is just happening randomly, and in such a situation just renaming the file and then building will help, (and it is possible that even without building it will be solved), and you can then revert back.
You can also completely disable warnings on Java Script under Tools -> Options -> Text Editor -> JScript -> Miscellaneous.
Of course in this case you will miss the Java Script warnings, but at least you will be able to concentrate on the server side warnings.

How to create regions in an aspx file?

I wonder is there any way we can create regions in aspx page as we create it in our cs pages.
not as Expandable, but in HTML it is normal to use the comments in order to create blocks of code
<!-- Start: Login access form -->
... Code ...
<!-- End: Login access form -->
Unfortunately no (at least not in Visual Studio).
You can select the commented section, then right click, collapse tag.
I don't think there's a way to do this.
However, I would suggest that if you are feeling the need to do this because your .aspx pages are very large, you might should look at redesigning it, or breaking it apart into User Controls (.ascx) or figure out a more effective use of master pages.
Not sure if that's the reason behind your question, but if it is, it's just a thought to pass on.
If you're using Visual Studio (could be the web essentials plugin, I can't remember if its native), the following snippet will be expandable in HTML files (including CSHTML). Unfortunately, these are not expandable in ASPX or ASCX files.
<!--#region Example -->
...code...
<!--#endregion Example -->
In an ASPX or ASCX file, perhaps you'd rather want to go with this:
<%-- START Example --%>
...code...
<%-- END Example --%>
They're still not expandable, but those will not get rendered out and therefore not be visible when right clicking on the page and viewing Source Code. You'll only see them in the development file.
P.S.
I didn't realize how old this question was until I finished typing out my answer. So I'm just going to go ahead and put this here anyway since it looks like it could use an update.
Visual Studio does a pretty good job of identifying elements with a significant amount of content to make it collapsable dynamically but thats the closest you going to get.
It might occur to you to place a series of element sibling in a DIV so that the div can be collapsed in visual studio. Thats very tempting but I would advise against it.
Regions are an IDE convenience that allow you to name a segment of code that may span multiple functions or procedures and be able to collapse/expand the whole segment as a whole. Visual Studio provides this feature only for code and not for HTML/ASPX/CSS portions of a file. For instance, you can create Regions within the <script runat="server"> section of an ASPX file.
You could use a div and put everything inside it

How do I remove fields from a web form using ASP?

I have a web page that has a web form for signing up. I want to remove fields. I've tried removing the field code from the .asp file but obviously there are other things that I need to remove along those lines. I have full access to all the code but I need help knowing where things are linked as far as making the form work again. Our programmer bailed.
A step by step guide would be great on this. thanks.
If they're just .ASP files, you should be fine removing the field tag, along with any references to it.
I.e. you'd delete this line:
<asp:TextBox id="text1" runat="server" />
and do a search for the 'id' attribute in the rest of the file (a find on 'text1' in this case), and remove those lines.
If everything to do with that for in in the same ASP page, it's easy. You can do a simple text search for the names and/or IDs of each form field. Sometimes they're referenced in a javascript block, so you'll have to comment-out some of the form validation code referencing those fields.
If they've used some dumb Dreamweaver script for all this - good luck!
If there are #include statements, or references to external JavaScript files it's more work - you'll have to trace through them as well, hoping they don't have their own included files as well.
After removing the input parts of the markup, if it is a .asp (assuming asp v3 instead of asp.net) it is also worth going through the <% %> tags part of the page to look for references to the removed inputs. If it's asp.net then check the vb.net / c# code in the script runat server block in the page, or look in the code behind file for references and recompile.

Using Javascript With ASP.Net controls

Is there a best practice when it comes to setting client side "onclick" events when using ASP.Net controls? Simply adding the onclick attribute results in a Visual Studio warning that onclick is not a valid attribute of that control. Adding it during the Page_Load event through codebehind works, but is less clear than I'd like.
Are these the only two choices? Is there a right way to do this that I'm missing?
Thanks!
Eric Sipple
**just a pre-note on the answer: HTML validation in VS is often BS. It complains about stuff that works IRL, even if that stuff is bad practice. But sometimes you gotta bend the rules to get stuff done.
Every ASP.NET page (2.0 and greater) comes with a ClientScriptManager. You use this to register javascript from server side code. You can pass in javascript that registers events on controls after the page has loaded, when the HTML controls on the page are all present in the DOM.
It presents a single, unified place on pages to dynamically add javascript, which isn't a bad thing. It is, however, awfully ugly.
In this time of the death of the ASP.NET server control model, you might want to set events the way they will be in the future of ASP.NET MVC. Grab a copy of jQuery and add it to your website. You can then easily register your events thusly:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("controlId").bind("click", function(e) { /* do your best here! */ });
});
</script>
</head>
<!-- etc -->
</html>
You can add the events through Javascript to the HTML elements that you want. This is the cleanest way, since it doesn't mix the server&client technologies. Furthermore, this way many handlers can be registered to the same event (in contrast to the onclick attribute).
Basically, the code would be
document.getElementById('myLovelyButtonId').attachEvent('onclick',doSomething)
for Internet Explorer and
document.getElementById('myLovelyButtonId').addEventListener('click',doSomething,false)
for other browsers. (doSomething is an event handler - JavaScript function). These calls should be made in the window load event handler
Consider reading the advanced event registration article on Quirksmode for further info.
Also, consider using a library like jQuery. This way, the statement will become
$('#myLovelyButtonId').click(
function doSomething () {
alert('my lovely code here');
});
Setting the value for WebControl.Attributes["onclick"] is okay. If ASP.NET needs a client-side click handler, it will concatenate the values, delimited by semi-colon.
Fix grammatical or spelling errors.
Clarify meaning without changing it.
Correct minor mistakes.
Add related resources or links.
Always respect the original author.

Resources