ASP.NET MVC Razor Syntax

4/4/2014·2 min read

few code tips for ASP.NET MVC Razor

1. add html attribute to your html
 	 @  Html.TextBoxFor(x => x.NewPassword, new  { @id = "txtId" , @class = "red"  })
 
2. write convert html, so following code will only display hello to the page
 	  @  Html.Raw("<p>hello</p>" )
 
3. another way to convert C# string to html.
   @(  new  HtmlString ("<p>hello2</p>" ) )
 
4. use text to add HTML
  <input  type="button"   @{  
 	  if  (flg)
 	  {
 		   <text>  id="testId"  </text>  
 	  }
 	  else 
 	  {
 		   <text>  id="testFakeId"  name="useme"  </text>  
 	  }
 	   }   />
 
5. save your value to javascript const, which able to use by javascript
 <script  type="text/javascript">
 var  test = window.test || {};
 test.data = {
 	newPassword: <span' @   Model.ConfirmPassword<span'< span=""> ,
 	oldPassword: <span'< span=""> 
 }
 </script>
 
6. At the beginning Razor view, you have to define ViewModel, which using its property at the page.
  @model   MvcApplication1.Models.ChangePasswordModel
 
7. adding common secion to parent page(Layout on MVC, Master page on ASP.NET)

So, just add section, anystring after section will be your name

  @section ScriptCommon{  
 	<script  type="text/javascript"></script>
  }
 

on the Layout page, add following syntax will render the child section

 	 @  RenderSection("ScriptCommon" , false )
 
8. using build-in @Helper syntax to ceate method on your Razor View
  @helper  TestValue(int value){
      <text>
      @ string.Format("hello{0}", value);
      </text>
 }
 
 
  @ TestValue(11112222)