Sunday, January 9, 2011

Razor Syntax Sheet

Syntax/Sample Web Forms Razor
Code Block
<%
  int x = 123; 
  string y = "because."; 
%>
@{ 
  int x = 123; 
  string y = "because.";
}
Expression (Html Encoded)
<%: model.Message %>
@model.Message
Expression (Unencoded)
<%= model.Message %>
@Html.Raw(model.Message)
Combining Text and markup
<% foreach(var item in items) { %>
  <%: item.Prop %>;
<% } %>;
@foreach(var item in items) {
  @item.Prop 
}
Mixing code and Plain text
<% if (foo) { %> 
  Plain Text 
<% } %>
@if (foo) {
  Plain Text 
}
Mixing code and plain text (alternate) Same as above
@if (foo) {
  @:Plain Text is @bar
}
Email Addresses Razor recognizes basic email format and is smart enough not to treat the @ as a code delimiter
Hi philha@example.com
Explicit Expression In this case, we need to be explicit about the expression by using parentheses.
ISBN@(isbnNumber)
Escaping the @ sign @@ renders a single @ in the response.
In Razor, you use the 
@@foo to display the value 
of foo
Server side Comment
<%--
This is a server side 
multiline comment
--%>
@*
This is a server side 
multiline comment 
*@
Mixing expressions and text
Hello <%: title %>. <%: name %>.
Hello @title. @name.

referenced from: haacked.com

Monday, March 22, 2010

Passing data while redirecting

In a controller action, while its required to redirect to some other action within same controller or action in other controller, it may require model/data to be passed too. The two simplest way to perform the same is
1. Me.TempData(some string in quotes) = your class object/Model
and this can be read at the target action code by using yourobject=Me.TempData(used string in quotes)

"Where are data stored? This can be configured via Controller.TempDataProvider property which has type ITempDataProvider. There are two main implementations of this interface – SessionTempDataProvider (standard) and CookieTempDataProvider (it’s suitable if we don’t want to enable sessions).
If we want to use some other temp-data-provider than SessionTempDataProvider then overrided Initialize method of Controller is very good place where we should assign instance of favorited temp-data-provider into TempDataProvider property." [From]

2. Using QueryString, like to redirect to action of other controller
Return RedirectToAction("action name", "controller name", your string to be passed)

and at the target action we can use this by using
Request.QueryString ( your object name )

Useful links:
[How do you test your Request.QueryString[] variables]
[refer1 refer2]