I know this might be a newbie question, but every-time i see code like this:
var table = $("table[title='Refresh']");
And also code like this:
$(function () {
$("#datepicker").datepicker();
});
i always sort of glaze over the $ symbol . It's a type of placeholder? or does it signify that its dynamic?
It is a JavaScript function, most likely jQuery. Many JS frameworks define $ as a root selector function, jQuery being the most famous/used of those.
It has nothing to do with ASP.NET.
The $ is not related to ASP.NET in particular, but rather to the possible use of jQuery or Prototype which both use the $ as an alias for a function. In the case of jQuery, $ is just a shortcut for not having to write jQuery as in the following example:
jQuery('selector').datepicker()
Is the same as writing
$('selector').datepicker()
jQuery provides the noConflict() method precisely to avoid conflicts with any other Javascript framework that may use the same $ alias.
This isn't part of ASP.NET, it's actually part of the JQuery library, which is a JavaScript library used for client side processing.
http://jquery.com/
It's the Shortcut / Alias to use in jQuery. Can be replaced with "jQuery " keyword."
This is jquery syntax of using $ symbol. Read more here http://www.learningjquery.com/2006/09/introducing-document-ready
That is JavaScript code. In JavaScript, $ is a legal name for a function or variable. It just means that someone defined a function with that name. You could define one yourself simply enough:
function $(){return "hello world";}
Then $() would print "hello world".
Most famously, JQuery uses it as their selector function, in which it is used to query the page's DOM in a more powerful syntax than JavaScript's built in DOM querying methods, but there's nothing that guarantees that $ is JQuery's usage, it could be anything. (Note that I highly discourage you from actually defining $ yourself and using it as a function, as virtually all JS developers have learned to read it as the JQuery's implementation.)
Related
Just a thought came in mind.
Why the first of these two tags does not work in asp.net?
To me both are string values whose final value is same. Which is value of attribute href of hyperlink.
Please make me understand it.
Test
Test
Note: I am not looking for solution to it. Only want to understand what's logically difference between these two case.
To me both are string values whose final value is same
Not really. Consider first if you just had a plain non-razor HTML form such as if you'd hard-coded the beginning of the path:
Test
Now, here "/SomeProject/Test/Index" is not a string. It's an attribute value in HTML. HTML has no concept of "string". Sure it happens to use the same delimiter as C# does for string, but this isn't C# here.
With Razor we have a few means to indicate we want something done by Razor to the otherwise plain HTML.
# is one of them, indicating that we want a C# expression evaluated and the result (if not void) output. And the result of (string.Format("~/Test/Index")) is ~/Test/Index so that is output.
~/ is, in certain contexts, another one, indicating that it should be replaced with the value of evaluating Href("~/") or Url.Content("~/"), which would be something like / or /SomeProject/ or whatever. It's not so much a string as something more like a keyword.
If you have an expression returning a string, you can still use strings similarly with:
Test
Which incidentally, was the only way this could be done in Razor 1.0. The direct parsing of "~/… was added as a convenience and it is indeed convenient.
I think you're misunderstanding what string.Format(string format, params Object[] args) does. It will only replace specified placeholders {0}, {1}, etc with provided paramters. Take a look at the docs in the link provided for more info.
In short it doesn't do any automatic replacement of environment variables or any other substitutions not already covered by the placeholders.
String.Format sits in the System namespace, therefore I wouldn't expect it to know anything about web sites, file systems or anything more complicated than simple placeholder substitution and formatting.
You should be using Url.Action i.e.
Test
or even easier
#Html.ActionLink("Test", "Index", "Test")
Also note that in ASP.Net MVC you don't use the full controller name, only the prefix i.e. Test instead of TestController
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'.
Is there a way to detect if an HTML page contains any razor/C# code? Essentially I want users to be able to provide custom layouts, with tags that I will replace with RenderSection. I want to validate that prior to making this replacement, that none of the HTML contains anything like for example, <a href="#(some C# code)".
All discussions about alternative ways to do this, should/could/would aside, just simply:
Is there a way to programmatically detect if a file contains C#/Razor code?
I don't know a lot about the Razor markup -- but I am thinking that when you grab the layout string they are passing in you will want to parse the text out and grab everything that starts with an # and toss those words into an array. Then, when you republish it to you website use razor code to access the data in the array...
Alternately, and easier, would be to go through all the passed in code and replace all the # signs with a different symbol say & that way it wont get interpreted by the Razor processor:
layoutString = layoutString.Replace('#', '&');
In the browser? No, because unless the programmer made a mistake, there is no Razor/C# code in teh rendered HTML, only HTML that was the result of that.
What you ask is like asking what type of oven was used to bake a pizza from the pizza. Bad news - you never will know.
If you provie sensible tags from those, you could parse them in javascript, but you have to output that metadata yourself as part of the generated html.
After reading your comment to TomTom; the answer is:
No. Razor does not come with any public syntax parser.
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.
I'm wondering if there's a jQuery-like css selector that can be used in C#.
Currently, I'm parsing some html strings using regex and thought it would be much nicer to have something like the css selector in jQuery to match my desired elements.
Update 10/18/2012
CsQuery is now in release 1.3. The latest release incorporates a C# port of the validator.nu HTML5 parser. As a result CsQuery will now produce a DOM that uses the HTML5 spec for invalid markup handling and is completely standards compliant.
Original Answer
Old question but new answer. I've recently released version 1.1 of CsQuery, a jQuery port for .NET 4 written in C# that I've been working on for about a year. Also on NuGet as "CsQuery"
The current release implements all CSS2 & CSS3 selectors, all jQuery extensions, and all jQuery DOM manipulation methods. It's got extensive test coverage including all the tests from jQuery and sizzle (the jQuery CSS selection engine). I've also included some performance tests for direct comparisons with Fizzler; for the most part CsQuery dramatically outperforms it. The exception is actually loading the HTML in the first place where Fizzler is faster; I assume this is because fizzler doesn't build an index. You get that time back after your first selection, though.
There's documentation on the github site, but at a basic level it works like this:
Create from a string of HTML
CQ dom = CQ.Create(htmlString);
Load synchronously from the web
CQ dom = CQ.CreateFromUrl("http://www.jquery.com");
Load asynchronously (non-blocking)
CQ.CreateFromUrlAsync("http://www.jquery.com", responseSuccess => {
Dom = response.Dom;
}, responseFail => {
..
});
Run selectors & do jQuery stuff
var childSpans = dom["div > span"];
childSpans.AddClass("myclass");
the CQ object is like thejQuery object. The property indexer used above is the default method (like $(...).
Output:
string html = dom.Render();
You should definitely see #jamietre's CsQuery. Check out his answer to this question!
Fizzler and Sharp-Query provide similar functionality, but the projects seem to be abandoned.
Not quite jQuery like, but this may help:
http://www.codeplex.com/htmlagilitypack
For XML you might use XPath...
I'm not entirely clear as to what you're trying to achieve, but if you have a HTML document that you're trying to extract data from, I'd recommend loading it with a parser, and then it becomes fairly trivial to query the object to pull desired elements.
The parser I linked above allows for use of XPath queries, which sounds like what you are looking for.
Let me know if I've misunderstood.