Looking for guide line about Razor syntax in asp.net mvc - asp.net-mvc

i am learning asp.net mvc just going through online tutorial
1) just see <span>#model.Message</span> and #Html.Raw(model.Message)
suppose if "Hello Word" is stored in Message then "Hello Word" should display if i write statement like
<span>#model.Message</span> but i just could not understand what is the special purpose about #Html.Raw(model.Message).
what #Html.Raw() will render ?
please discuss with few more example to understand the difference well.
2) just see the below two snippet
#if (foo) {
<text>Plain Text</text>
}
#if (foo) {
#:Plain Text is #bar
}
in which version of html the tag called was introduce. is it equivalent to or what ? what is the purpose of
this tag ?
just tell me about this #:Plain Text is #bar
what is the special meaning of #: ?
if our intention is to mixing text with expression then can't we write like Plain Text is #bar
3) <span>ISBN#(isbnNumber)</span>
what it will print ? if 2000 is stored in isbnNumber variable then it may print <span>ISBN2000</span>. am i right ?
so tell me what is the special meaning of #(variable-name) why bracket along with # symbol ?
4) just see
<span>In Razor, you use the
##foo to display the value
of foo</span>
if foo has value called god then what this ##foo will print ?
5 ) see this and guide me about few more syntax given below point wise
a) #(MyClass.MyMethod<AType>())
b)
#{
Func<dynamic, object> b =
#<strong>#item</strong>;
}
#b("Bold this")
c) <div class="#className foo bar"></div>
6) see this
#functions
{
string SayWithFunction(string message)
{
return message;
}
}
#helper SayWithHelper(string message)
{
Text: #message
}
#SayWithFunction("Hello, world!")
#SayWithHelper("Hello, world!")
what they are trying to declare ? function ?
what kind of syntax it is ?
it seems that two function has been declare in two different way ? please explain this points with more sample. thanks
Few More question
7)
#{
Func<dynamic, object> b = #<strong>#item</strong>;
}
<span>This sentence is #b("In Bold").</span>
what the meaning of above line ? is it anonymous delegate?
when some one will call #b("In Bold") then what will happen ?
8)
#{
var items = new[] { "one", "two", "three" };
}
<ul>
#items.List(#<li>#item</li>)
</ul>
tell me something about List() function and from where the item variable come ?
9)
#{
var comics = new[] {
new ComicBook {Title = "Groo", Publisher = "Dark Horse Comics"},
new ComicBook {Title = "Spiderman", Publisher = "Marvel"}
};
}
<table>
#comics.List(
#<tr>
<td>#item.Title</td>
<td>#item.Publisher</td>
</tr>)
</table>
please explain briefly the above code. thanks

1) Any kind of #Variable output makes MVC automatically encode the value. That is to say if foo = "Joe & Dave", then #foo becomes Joe & Dave automatically. To escape this behavior you have #Html.Raw.
2) <text></text> is there to help you when the parser is having trouble. You have to keep in mind Razor goes in and out of HTML/Code using the semantics of the languages. that is to say, it knows it's in HTML using the XML parser, and when it's in C#/VB by its syntax (like braces or Then..End respectively). When you want to stray from this format, you can use <text>. e.g.
<ul>
<li>
#foreach (var item in items) {
#item.Description
<text></li><li></text>
}
</li>
</ul>
Here you're messing with the parser because it no longer conforms to "standard" HTML blocks. The </li> would through razor for a loop, but because it's wrapped in <text></text> it has a more definitive way of knowing where code ends and HTML begins.
3) Yes, the parenthesis are there to help give the parser an explicit definition of what should be executed. Razor makes its best attempt to understand what you're trying to output, but sometimes it's off. The parenthesis solve this. e.g.
#Foo.bar
If you only had #Foo defined as a string, Razor would inevitably try to look for a bar property because it follows C#'s naming convention (this would be a very valid notation in C#, but not our intent). So, to avoid it from continuing on we can use parenthesis:
#(Foo).bar
A notable exception to this is when there is a single trailing period. e.g.
Hello, #name.
The Razor parser realizes nothing valid (in terms of the language) follows, so it just outputs name and a period thereafter.
4) ## is the escape method for razor when you need to actually print #. So, in your example, you'd see #foo on the page in plain text. This is useful when outputting email addresses directly on the page, e.g.
bchristie##contoso.com
Now razor won't look for a contoso.com variable.
5) You're seeing various shortcuts and usages of how you bounce between valid C# code and HTML. Remember that you can go between, and the HTML you're seeing is really just a compiled IHtmlString that is finally output to the buffer.

1.
By default, Razor automatically html-encodes your output values (<div> becomes <div>). #Html.Raw should be used when you explicitly want to output the value as-is without any encoding (very common for outputting JSON strings in the middle of a <script>).
2.
The purpose of <text> and #: is to escape the regular Razor syntax flow and output literal text values. for example:
// i just want to print "Haz It" if some condition is true
#if (Model.HasSomething) { Haz It } // syntax error
#if (Model.HasSomething) { <text>Haz It</text> } // just fine
As of #:, it begins a text literal until the next line-feed (enter), so:
#if (Model.HasSomething) { #:Haz It } // syntax error, no closing '}' encountered
// just fine
#if (Model.HasSomething)
{
#:Haz It
}
3.
By default, if your # is inside a quote/double-quotes (<tr id="row#item.Id"), Razor interprets it as a literal and will not try to parse it as expression (for obvious reasons), but sometimes you do want it to, then you simply write <tr id="row#(item.Id").
4.
The purpose of ## is simply to escape '#'. when you want to output '#' and don't want Razor to interpret is as an expression. then in your case ##foo would print '#foo'.
5.
a. #(MyClass.MyMethod<AType>()) would simply output the return value of the method (using ToString() if necessary).
b. Yes, Razor does let you define some kind of inline functions, but usually you better use Html Helpers / Functions / DisplayTemplates (as follows).
c. See above.
6.
As of Razor Helpers, see http://weblogs.asp.net/scottgu/archive/2011/05/12/asp-net-mvc-3-and-the-helper-syntax-within-razor.aspx

Related

How to render HTML predefined tag in Razor view?

I want to render the HTML predefined tag (between h2 to h6) based on what is set in my model. Below is the snippet. I am facing issue in my closing tag. closing tag is not processed and it is considered as text and it is truncated in the page view source.
string subArticleLevel = "h2";
if(subarticle.SubTitleLevel!=null)
{
subArticleLevel = subarticle.SubTitleLevel;
}
<#subArticleLevel>#subarticle.SubTitle</#subArticleLevel>
You can use Html.Raw method with explicit code block notation.
#Html.Raw("<")#(subArticleLevel)#Html.Raw(">")#(subarticle.SubTitle)
#Html.Raw("</")#(subArticleLevel)#Html.Raw(">")
Or
Simply use #: prefix to denote it is a start of an html block, if you are already in a code block. The below should work fine.
#{
string subArticleLevel = "h2";
string subarticleSubTitle = "test";
#:<#subArticleLevel>#subarticleSubTitle</#subArticleLevel>
}
I'm not sure what version of MVC you are on but if you have c# 6 you might just use c# string interpolation.
#($"<{subArticleLevel}>{subarticle.SubTitle}</{subArticleLevel}>")
I haven't tried it but if you are getting html encoding you could try.
#Html.Raw($"<{subArticleLevel}>{subarticle.SubTitle}</{subArticleLevel}>")
If you don't have c# 6 available you can try .
#Html.Raw(string.Format("<{0}>{1}</{0}>", subArticleLevel, subarticle.SubTitle))

How to show String new lines on gsp grails file?

I've stored a string in the database. When I save and retrieve the string and the result I'm getting is as following:
This is my new object
Testing multiple lines
-- Test 1
-- Test 2
-- Test 3
That is what I get from a println command when I call the save and index methods.
But when I show it on screen. It's being shown like:
This is my object Testing multiple lines -- Test 1 -- Test 2 -- Test 3
Already tried to show it like the following:
${adviceInstance.advice?.encodeAsHTML()}
But still the same thing.
Do I need to replace \n to or something like that? Is there any easier way to show it properly?
Common problems have a variety of solutions
1> could be you that you replace \n with <br>
so either in your controller/service or if you like in gsp:
${adviceInstance.advice?.replace('\n','<br>')}
2> display the content in a read-only textarea
<g:textArea name="something" readonly="true">
${adviceInstance.advice}
</g:textArea>
3> Use the <pre> tag
<pre>
${adviceInstance.advice}
</pre>
4> Use css white-space http://www.w3schools.com/cssref/pr_text_white-space.asp:
<div class="space">
</div>
//css code:
.space {
white-space:pre
}
Also make a note if you have a strict configuration for the storage of such fields that when you submit it via a form, there are additional elements I didn't delve into what it actually was, it may have actually be the return carriages or \r, anyhow explained in comments below. About the good rule to set a setter that trims the element each time it is received. i.e.:
Class Advice {
String advice
static constraints = {
advice(nullable:false, minSize:1, maxSize:255)
}
/*
* In this scenario with a a maxSize value, ensure you
* set your own setter to trim any hidden \r
* that may be posted back as part of the form request
* by end user. Trust me I got to know the hard way.
*/
void setAdvice(String adv) {
advice=adv.trim()
}
}
${raw(adviceInstance.advice?.encodeAsHTML().replace("\n", "<br>"))}
This is how i solve the problem.
Firstly make sure the string contains \n to denote line break.
For example :
String test = "This is first line. \n This is second line";
Then in gsp page use:
${raw(test?.replace("\n", "<br>"))}
The output will be as:
This is first line.
This is second line.

jQuery Mobile Filtered List - only match beginning of string

Im using the jQuery mobile search filter list:
http://jquerymobile.com/test/docs/lists/lists-performance.html
Im having somer performance issues, my list is a little slow to filter on some phones. To try and aid performance I want to change the search so only items starting with the search text are returned.
So 'aris' currently finds the result 'paris' but I want this changed. I can see its possible from the documentation below but I dont know how to implement the code.
http://jquerymobile.com/test/docs/lists/docs-lists.html
$("document").ready( function (){
$(".ui-listview").listview('option', 'filterCallback', yourFilterFunction)
});
This seems to demonstrate how you write and call your own function, but ive no idea how to write it! Thanks
http://blog.safaribooksonline.com/2012/02/14/jquery-mobile-tip-write-your-own-list-view-filter-function/
UPDATE - Ive tried the following in a seperate js file:
$("document").ready( function (){
function beginsWith( text, pattern) {
text= text.toLowerCase();
pattern = pattern.toLowerCase();
return pattern == text.substr( 0, pattern.length );
}
$(".ui-listview").listview('option', 'filterCallback', beginsWith)
});
might look something like this:
function beginsWith( text, pattern) {
text= text.toLowerCase();
pattern = pattern.toLowerCase();
return pattern == text.substr( 0, pattern.length );
}
Basically you compare from 0 to "length" of what you're matching to the source. So if you pass in "test","tester" it will see you're passing in a string of length 4 and then substr "tester" from 0,4, which gives you "test". Then "test" is equal to "test"... so return true. Lowercase them to make it case insensitive.
Another trick to improve filter performance, only filter once they've entered more than 1 character.
edit it appears jQueryMobile's filter function expects that "true" means it was not found... so it needs to be backwards. return pattern != text.substr( 0, pattern.length );
This worked for me. I am using regular expression here so sort of different way to achieve the same thing.
But the reason why my code didn't work initially was that the list item had a lot of spaces at the beginning and at the end (found that it got added on it's own while debugging).
So I do a trim on the text before doing the match. I have a feeling Jonathan Rowny's implementation will also work if we do text.trim() before matching.
$(".ui-listview").listview('option', 'filterCallback', function (text, searchValue) {
var matcher = new RegExp("^" + searchValue, "i");
return !matcher.test(text.trim());
});

grails/groovy braces syntax question

I'm working with an example that I can't understand what the braces do -- the ones around the "Logout" in the second "out" statement below. I guess the string is passed as a closure but I'm not getting the syntax beyond that. Can you please clarify? Note the output of the code looks like the following:
John Doe [Logout]
class LoginTagLib {
def loginControl = {
if(request.getSession(false) && session.user){
out << "Hello ${session.user.login} "
out << """[${link(action:"logout",
controller:"user"){"Logout"}}]"""
} else {
out << """[${link(action:"login",
controller:"user"){"Login"}}]"""
}
}
}
Thanks Much
The link tag takes attributes and a body, and as a regular GSP tag it's called like this:
<g:link action="logout" controller="user">Logout</g:link>
To invoke it as a method like you're doing, you need a way to pass the text ('Logout') to render in the link. If you look at the source of the tag (click "Show Source" at the bottom of http://grails.org/doc/latest/ref/Tags/link.html) you'll see that the 2nd argument is body, and it's a Closure (although that's not clear from the code, but that's always the case for 2-parameter tags). {"Logout"} is a Closure that returns "Logout" since it's the last expression, so it's used as the body.
Actually the output should be
Hello John Doe [Logout]
Essentially, if there is a session and a user write Hello user and create a link pointing to a logout action with the label Logout.
{ "Logout" } is a closure equivalent to { return "Logout"; } as the last statement is used for a return value if none is explicitly stated.
I am not able to get the output like below
Hello John Doe [Logout]
Here is the output I am getting
Hello jdoe [Logout

How to parse a remote website and create a link on every single word for a dictionary tooltip?

I want to parse a random website, modify the content so that every word is a link (for a dictionary tooltip) and then display the website in an iframe.
I'm not looking for a complete solution, but for a hint or a possible strategy. The linking is my problem, parsing the website and displaying it in an iframe is quite simple. So basically I have a String with all the html content. I'm not even sure if it's better to do it serverside or after the page is loaded with JS.
I'm working with Ruby on Rails, jQuery, jRails.
Note: The content of the href tag depends on the word.
Clarification:
I tried a regexp and it already kind of works:
#site.gsub!(/[A-Za-z]+(?:['-][A-Za-z]+)?|\\d+(?:[,.]\\d+)?/) {|word| '' + word + ''}
But the problem is to only replace words in the text and leave the HTML as it is. So I guess it is a regex problem...
Thanks for any ideas.
I don't think a regexp is going to work for this - or, at least, it will always be brittle. A better way is to parse the page using Hpricot or Nokogiri, then go through it and modify the nodes that are plain text.
It sounds like you have it mostly planned out already.
Split the content into words and then for each word, create a link, such as whatever
EDIT (based on your comment):
Ahh ... I recommend you search around for screen scraping techniques. Most of them should start with removing anything between < and > characters, and replacing <br> and <p> with newlines.
I would use Nokogiri to remove the HTML structure before you use the regex.
no_html = Nokogiri::HTML(html_as_string).text
Simple. Hash the HTML, run your regex, then unhash the HTML.
<?php
class ht
{
static $hashes = array();
# hashes everything that matches $pattern and saves matches for later unhashing
function hash($text, $pattern) {
return preg_replace_callback($pattern, array(self,'push'), $text);
}
# hashes all html tags and saves them
function hash_html($html) {
return self::hash($html, '`<[^>]+>`');
}
# hashes and saves $value, returns key
function push($value) {
if(is_array($value)) $value = $value[0];
static $i = 0;
$key = "\x05".++$i."\x06";
self::$hashes[$key] = $value;
return $key;
}
# unhashes all saved values found in $text
function unhash($text) {
return str_replace(array_keys(self::$hashes), self::$hashes, $text);
}
function get($key) {
return self::$hashes[$key];
}
function clear() {
self::$hashes = array();
}
}
?>
Example usage:
ht::hash_html($your_html);
// your word->href converter here
ht::unhash($your_formatted_html);
Oh... right, I wrote this in PHP. Guess you'll have to convert it to ruby or js, but the idea is the same.

Resources