My ASP.NET MVC3 Notes(3)

03 – Ajax and Javascript

Razor helper is similar to function in javascript, it can be defined in View using it or in a separate Razor View file

In _layout view there are two lines of code to import javascript:

    <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/modernizr-1.7.min.js")" type="text/javascript"></script>

if we define a Razor helper for loading script:

@helper Script(string scriptName){
     <script src="@Url.Content("~/Scripts/"+scriptName)" type="text/javascript"></script>
}

then the previous code can be replaced with:

@*    
    <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/modernizr-1.7.min.js")" type="text/javascript"></script>
*@
    @Script("jquery-1.5.1.min.js")
    @Script("modernizr-1.7.min.js")

If we want to make this helper global, we can create a separate view file under \App_Code folder. This Razro View file will logically compile down to a static class (with the name of file name Content)  with static members of “Script”  within it.

image
@*Content.cshtml*@
@using System.Web.Mvc

@helper Script(string scriptName, UrlHelper url){
     <script src="@url.Content("~/Scripts/"+scriptName)" type="text/javascript"></script>
}

and then the _Laout.cshtml should be modified like this:

@*    
    <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/modernizr-1.7.min.js")" type="text/javascript"></script>

    @Script("jquery-1.5.1.min.js")
    @Script("modernizr-1.7.min.js")
*@
    @Content.Script("jquery-1.5.1.min.js", Url)
    @Content.Script("modernizr-1.7.min.js",Url)
  • Dynamically load script with expected order

when running a particular View which loads a particular script, we often need to make sure that this script is loaded after some other script, such as jquery.js. In this case we can use @RenderSection to load this script dynamically.

@* _Layout.cshtml *@
    @Content.Script("jquery-1.5.1.min.js", Url)
    @Content.Script("modernizr-1.7.min.js",Url)
    @RenderSection("script", false)

In a particular View, for instance, Edit.cshtml, the scripts needed to load should be put into a section

image
  • jQuery Template

    • Create markup template in View

image
  •  
    • Get JSON object from server side and then apply to the template
image
  • Comparison

Method

Code Type

Data Type

HTML Helper C#  (Sever side) C# parameters
Razor Helper Html + Razor C# parameters
Parial View Html + Razor Model object
jQuery Template Html + Razor JSON object
posted @ 2011-06-14 06:02  Jian, Li  Views(634)  Comments(0)    收藏  举报