Visual Studio confused by server code inside javascript - asp.net

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.

Related

Error converting from a .htm to .aspx file

I swapped my index.htm to default.aspx which contains some vbscript but for some odd reason it worked as a .htm but as an .aspx page is gives me this error:
BC30289: Statement cannot appear within a method body. End of method assumed.
Is there a quick simple fix for this? or do I have to reprogram my vbscript to work around C# or VB? Any ideas?
Assuming your vbscript is meant to be client-side, the change to .aspx might be running the vbscript as server code instead of client-side code. Try putting the vbscript in a script element:
<script>
' vbscript code...
</script>
If you do want the VB to run on the server instead of the client, make sure you are not declaring another function within the Page_Load() function. You can't declare a function within a function.
It would also be helpful to see your code.
You might want to check that your code is placed properly within your .aspx page.
<script runat="server" language="vb">
</script>

Is MVC 2 client-side validation broken in Visual Studio 2010 RC?

I can't seem to get client side validation working with the version of MVC released with Visual Studio 2010 RC.
I've tried it with two projects -- one upgrade from 1.0, and one using the template that came with VS.
I'd think the template version would work, but it doesn't. Added the following scripts:
<script type="text/javascript"
src="<%= Url.Content("~/Scripts/MicrosoftMvcValidation.js") %>">
</script>
<script type="text/javascript"
src="<%= Url.Content("~/Scripts/jquery.validate.js")%>">
</script>
which are downloaded to the client correctly. Added the following to my form page:
<% Html.EnableClientValidation(); %>
<%--yes, am aware of the EndForm() bug! --%>
<% using (Html.BeginForm()) { %>
<%--snip --%>
and I can see the client validation scripts have been added to the bottom of the form. But still client validation never happens.
What is worse is that in my upgraded project, the client validation scripts are never output in the page!
PLEASE NOTE: I am specifically asking about the version of MVC2 that came with VS2010 RC. Also, I do know how to google; please don't waste anybody's time searching and answering if you aren't familiar with this issue in the release candidate of Visual Studio. Thanks.
Error ID10T: User editing one page and testing another.
However, I can't get client-side validation working on the MVC2 template project. If anybody has an idea how to, say, get it working for the registration page, please answer.
I had the same problem also,
the examples by MS(scottGu and haacked) are a bit confusing since you don't really know on which version they are talking about, and haacked updates his post every time a new version is out so you it's not relevant to you :(.
To make jQuery validation work On VS 2010 do the following:
as you answered you need the MicrosoftMvcJQueryValidation.js file, several ways to get this file, i got it from the example project from haacked post: ASP.NET MVC 2 Custom Validation
remove all JS references and leave just this one and the jquery.validate.min.js
call <% Html.EnableClientValidation(); %> before the opening tag of the form
Dont forget to put some Html.ValidationMessageFor(.. on your fields since this is the trigger for adding the enteries to the client validation JSON object
i guess you did all the above, but left the references to MicrosoftMvcValidation.js on the page, notice at the end of this file there is the hook to the MS client side validation.
funny i just wanted to blog about this issue this morning and found your question,\hope this helps
I have had no luck getting this to work in MVC 2 RC. According to other questions here on SO, you have to get the MicrosoftMvcJQueryValidation.js file from the MVC Futures release, hold your left foot behind your head, and whistle Dixie for half an hour. I did this and more and have not been able to make it work.
I have, however, gotten it working by using the jQuery Validation plugin directly. More work, but it gets the job done.
Hopefully it will be fixed in RTM.

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

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.

How to implement A simple AJAX call using asp.net page?

I'm trying to implement this specific example using asp.net page instead of asp page.
If you look at the example you can see that there are 2 parts for the page:
Mail asp page. This page have JS code that calls other asp file for AJAX use.
the other asp page which holds the JS code.
The responseText of the call is the client side code, so, when I write something like this:
<html><head><title>test</title><script language="javascript" runat="server"
type="text/javascript">function test(){Response.Write("This is a Test!");
</script><body onload="test()"></body></html>
the page ignores my server side code and returns this:
<html><head><title>test</title><body onload="test()"></body></html>
what should I need to do to make him process my JS code and return its output?
Thanks in advance,
Oz Radiano.
asp.net does not process javascript server side, so setting the script tag runat=server with language="javascript" will be mostly ignored.
I think if you change it to "JScript" it will work, however, this has nothing to do with ajax.
"runat = server" says, preprocess this on the server and don't send it to the client.
If the language is a processable one it will be evaluated as well.
Try implementing the example after watching some videos from http://www.asp.net/learn/ajax-videos/ and http://www.asp.net/learn/ajax/
Its very easy to implement AJAX in asp.net then ASP. I can clearly give you the correct source code. :) But you seem to try out new things. Let us know how it goes!
Thanks for your responses, they made me understand that I'm not sure what my problem is.
After failing in implementing this exact example, I've googleed "how to run asp code using ajax"
this result returned and made it very clear.
Thanks again.

Microsoft MVC "echo/print/output" etc

With ASP.NET's view engine/template aspx/ashx pages the way to spit to screen seems to be:
<%= Person.Name %>
Which was fine with webforms as alot of model data was bound to controls programatically. But with MVC we are now using this syntax more oftern.
The issue I have with it is quite trivial, but annoying either way. This is that it seems to break up the mark up i.e.:
<% foreach(var Person in People) { %>
<%= Person.Name %>
<% } %>
That seems like alot of opening and closing tags to me!
Other view engines in the MVC contrib have a means of spitting to screen with out opening and closing the script tags using standard keyword such as "print, out, echo" i.e. (brail example):
<%
for element in list:
output "<li>${element}</li>"
end
%>
Now, I said this may seem trivial, but it just seems more readable this way. So what are the advantages of MS having this syntax, and not providing a output method?
Cheers, Chris.
Consider something like this, instead:
<% foreach(var Person in People) {
Response.Write(Person.Name);
} %>
I believe that'll work. (Although I haven't tested it; I've only just begun with MVC and don't have the toolset here at the office.)
EDIT: I apparently missed the actual question ... :)
Microsoft does provide an output method, but didn't provide a syntax like the one you describe. The output method is Response.Write(). I can't answer this directly (I believe you'll need to check with Scott Hanselmann over at MS :)), but I think they didn't want to complicate scripting by adding yet-another-language for us to learn; I think they wanted to leverage the languages (C#, VB, etc.) which developers already knew.
EDIT #2: I placed the following in a comment, and in retrospect (for completeness), it should be part of the answer.
If you head over to the Learn MVC site on ASP.NET, in the view tutorial (that's the link), you'll see the following paragraph:
Since you call Response.Write() so
often, Microsoft provides you with a
shortcut for calling the
Response.Write() method. The view in
Listing 3 uses the delimiters <%= and
%> as a shortcut for calling
Response.Write().
Essentially, <%= %> is the accepted shortcut for Response.Write, and you therefore can use the full Response.Write method anywhere you'd use <%= %>.
My answer is based on personal XP with MVC4 cshtml - you can use:
#Html.Raw("SomeStringDirectlyInsideTheBrowserPageHTMLCode")
This renders the (dynamic) string at its position unlike Response.Write(MyString) which as far as I've noticed always renders the string at the begining of the browser-page.
Note that the HTML tags rendered by #Html.Raw(MyString) cannot be checked by the compiler. I mean: #Html.Raw("<div ....>") cannot be closed by mere </div> because you will get an error (<div ....> is not detected by the compiler) so you must close the tag with #Html.Raw("</div>")
P.S.In some cases this doesn't work (for example it fails within DevExpress) - use ViewContext.Writer.Write() or ViewContext.Writer.WriteLine() instead.
What you're looking for is probably a different View engine -- they each handle embedded code like that in their own way. Check out NHaml, an ASP.Net port of Rails' Haml engine.
Some more view engines to look at: Brail,
NVelocity
Thanks guys,I dont specifically want to switch view engines, though I will take time to look at the other avaliable. I am sure you can understand that most MS development houses dont touch anything but MS branded technology so I just wanted to know if there was a way to do this with the default view engine. Or if not, why not? Is there a reason, if not where could I suggest the default view compiler add such a keywork.
John- I believe that Response.Write(Person.Name) will just render the string to the top of the page, before any other output. Not 100% on that though, ill give it a bash.
Edit:
Apparently, Response.Write(Person.Name) works as suggested. Well that was easy. Thanks :-) John.
I've heard they're working on improving this for ASP.Net 4 via client templates.
Another option other than Response.Write would be to write XHtml with XSL transformations

Resources