ASP.NET Razor 視圖引擎編程參考

來源:互聯網
上載者:User

標籤:des   style   blog   http   color   os   io   for   ar   

轉載請註明出處:http://surfsky.cnblogs.com

Rasor 視圖引擎
    http://msdn.microsoft.com/zh-cn/library/ff849693.aspx
    http://www.microsoft.com/downloads/en/details.aspx?FamilyID=b7937c34-3b53-47b7-ae17-5a72fa700472&displaylang=en
    http://aspnet.codeplex.com/wikipage?title=WebPages&referringTitle=Home

    優點:“幹練簡單”

    可以用它來做MVC視圖引擎,也可以直接用它來編寫傳統類似php式的網站,非常輕便。


文法識別
    嵌入變數
        <h3>Hello @name, the year is @DateTime.Now.Year </h3>
        <a href="/products/details/@productId">the product</a>
    運算式(括弧)
        <p>Your message : @("Number is: " + number) </p>
    代碼塊(花括弧)
        @{
          int number = 1;
          string message = "Number is " + number;
        }
        @{ var myQuote = @"The person said: ""Hello, today is Monday."""; }
    <text>標籤
        if (i > 0) { 
          <text>;</text> 
        }
    智能區別@
        <p>mail [email protected] telling : @Date.Now.</p>
        可以顯式地打@@來用另外一個”@”字元進行轉義
    
判斷
    @if(products.Count == 0){
      <p>Sorry - no products in this category </p>
    }else{
      <p>We have a products for you!</p>
    }
    @if (DateTime.Now.Year == 2010){
      <span>
        the date: @DateTime.Now
      </span>
    }
    
迴圈
    <ul id="products">
      @foreach(var p in products){
        <li>@p.Name ([email protected]) </li>
      }
    </ul>

模板
    <!DOCTYPE html>
    <html>
      <body>
        <div>@RenderSection("menu", optional:true)</div>
        <div>@RenderBody()</div>
        <div>@RenderSection("footer", optional:true)</div>
      </body>
    </html>
    -----------------------------
    @{LayoutPage = "sitelayout.cshtml";}
    <p>current datetime: @DateTime.Now</p>
    @section menu{
      <ul id="sub-menu">
        <li>item1</li>
        <li>item2</li>
      </ul>
    }
    @section footer{
      <p>this is my custom footer</p>    
    }
    
輔助函數
    @Html.LabelFor(m => m.ProductID)
    @Html.TextBoxFor(m => m.ProductID)
    @Html.ValidationMessageFor(m => m.ProductID)
    
建立輔助函數
    @helper ProductListing(List<Product> products){
      <ul>
        @foreach(var p in products){
          <li>@p.Name ([email protected])</li>
        }
      </ul>
    }
    <div>@ProductListing(Model.Products)</div>
    
函數參數
    <h1>small bakery products</h1>
    @Grid.Render(
      data: Model.products,
      tableStyle: "grid",
      headerStyle: "head",
      alternationRowStyle: "alt",
      columns: Grid.Columns(
        Grid.Column("Name", "Product", style:"Product"),
        Grid.Column("Description", format:@(<i>@item.Description</i>),
        Grid.Column("Price", format:@<span>[email protected]</span>)
      )
    )

函數
    @using  System.Text;      
    @functions  {
      public  static  IHtmlString  Repeat(int  times,  Func<int,  object>  template)  {      
        StringBuilder  builder  =  new  StringBuilder();      
        for(int  i  =  0;  i  <  times;  i++)  {
          builder.Append(template(i));
        }
        return  new  HtmlString(builder.ToString());
      }      
    }
    @Repeat(10, @<li>List Item</li>);
    @Repeat(10, @<li>List Item #@item</li>);

類型轉換
    var myStringNum = "539";
    var myStringBool = "True";
    var myStringFloat = "41.432895";
    var myStringDec = "10317.425";
    var myDateString = "12/27/2010";
    -------------------------------
    if(myStringNum.IsInt()==true)
    var myIntNumber = myStringNum.AsInt();
    var myVar = myStringBool.AsBool();
    var myFloatNum = myStringFloat.AsFloat();
    var myDecNum = myStringDec.AsDecimal();
    var newDate = myDateString.AsDateTime();


檔案
    訪問cshtml檔案均無需加副檔名。如:~/Gallery/Index
    底線開始的cshtml檔案不能單獨運行(一般是做為模板檔案、公用控制項)
    幾個特殊檔案
        _init.cshtml
          @{
            // Set the layout page for the whole site
            LayoutPage = "_Master.cshtml";
          }
        _start.cshtml
          @{
            WebSecurity.InitializeDatabaseConnection("PhotoGallery", "UserProfiles", "UserId", "Email", true);
          }
        
  
--------------------------------
-- more
--------------------------------
@Inherits System.Web.Mvc.WebViewPage
    View.Title = "Home Page";
    LayoutPage = "~/Views/Shared/_layout.cshtml";
    View.Message

Login
    check
        if (WebSecurity.IsAuthenticated){
          歡迎您,<b>@WebSecurity.CurrentUserName</b>!
          @Html.ActionLink("登出", "LogOff", "Account")
        }
        else{
          @Html.ActionLink("登入", "LogOn", "Account")
        }
        @if (WebSecurity.IsAuthenticated) {
            <span>Welcome <b><a href="@Href("~/Account/ChangePassword")">@WebSecurity.CurrentUserName</a></b>!
            [ <a href="@Href("~/Account/Logout")">Logout</a> ]</span>
        } else {
            <span>[ <a href="@Href("~/Account/Login")">Login</a> | <a href="@Href("~/Account/Register")">Register</a> ]</span>
        }
    login
        // Attempt to login to the Security object using provided creds
        if (WebSecurity.Login(username, password, rememberMe)) {
            Response.Redirect("~/");
        }
    logout
        WebSecurity.Logout();
    regist
        WebSecurity.CreateAccount(email, password, requireEmailConfirmation)
        WebSecurity.ConfirmAccount(confirmationToken)
        WebSecurity.GetUserId(email)
        WebSecurity.GeneratePasswordResetToken(email)
    password
        WebSecurity.ResetPassword(passwordResetToken, newPassword)
        WebSecurity.ChangePassword(WebSecurity.CurrentUserName, currentPassword, newPassword)
            
Template
    @RenderPage("/Shared/_Header.cshtml")
    @RenderPage("/Shared/_Footer.cshtml")
    @RenderBody()
    @RenderSection("fffff")

microsoft sql server compact edition
    var db = Database.OpenFile("database.sdf");
    var sql = "select * from table1";
    var data = db.Query(sql);
    Database.Execute(sql)
    
fileupload
    @FileUpload.GetHtml(
      initialNumberOfFiles: 1,
      allowMoreFilesToBeAdded: false,
      includeFormTag: true,
      uploadText: "Upload"
      )

Image
    WebImage.Resize();
    WebImage.FlipVertical();
            .FlipHorizontal();
            .FlipLeft();
            .FlipRight();
    WebImage.AddTextWatermark();
    WebImage.AddImageWatermark();

Video
    @Video.Flash(
        path: "testFlash.swf",
        width: "400",
        height: "600",
        play: true,
        loop: true;
        menu: false,
        bgColor: "red",
        quality: "medium",
        scale: "exactfit",
        windowMode: "transparent"
        );
    @Video.MediaPlayer()
    @Video.Silverlight()

Toolkit(Microsoft.WebPages.Helpers.Toolkit.dll)
    Twitter
        @Twitter.Profile("haacked")
    Facebook
    Gravator
    Recaptcha
        
Form Postback
    <form action="" method="post">
        <p>
          <label for="text1">First Number:</label>
          <input type="text" name="text1" />
        </p>
        <p>
          <label for="text2">Second Number:</label>
          <input type="text" name="text2" />
        </p>
        <p><input type="submit" value="Add" /></p>
    </form>
    <p>@totalMessage</p>
    @{
        var totalMessage = "";
        if(IsPost) {
            var num1 = Request["text1"];
            var num2 = Request["text2"];
            var total = num1.AsInt() + num2.AsInt();
            totalMessage = "Total = " + total;
        }
    }

mail
    Mail.Send(
      to: email, 
      subject: "Please reset your password", 
      body: "Use this password reset token to reset your password. The token is: " + resetToken + @". Visit <a href=""" + resetUrl + @""">" + resetUrl + "</a> to reset your password."
    );
    Mail.SmtpServer.IsEmpty()
        
--------------------------------
-- 可用的 MVC 輔助函數和輔助類
--------------------------------
@Inherits System.Web.Mvc.WebViewPage
@Inherits System.Web.Mvc.WebViewPage<IList<RasorSample.Models.Category>>
@model LIst<Product>

@PageData["Title"]       用於頁面內資料共用,如masterpage和contentpage共用
@Href("~/Site.css")      擷取url
@WebSecurity             封裝了使用者安全相關函數
@UrlData[0]              應該等效於Request["..."]
@Html.PageLink("View", (string)similarTags[i].TagName, (string)similarTags[i].TagName)
<a href="@HrefAttribute("View", tag.TagName)">

ASP.NET Razor 視圖引擎編程參考

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.