zoukankan      html  css  js  c++  java
  • ASP.NET Razor 视图引擎编程参考

    ASP.NET Razor 视图引擎编程参考

     

    转载请注明出处: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 scottgu@microsoft.com 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 ($@p.Price) </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 ($@p.Price)</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>$@item.Price</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",
            "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)">

    转载请注明出处:http://surfsky.cnblogs.com 

  • 相关阅读:
    LintCode Python 简单级题目 488.快乐数
    LintCode Python 简单级题目 100.删除排序数组中的重复数字 101.删除排序数组中的重复数字II
    LintCode Python 简单级题目 373.奇偶分割数组
    LintCode Python 简单级题目 39.恢复旋转排序数组
    LintCode Python 简单级题目 35.翻转链表
    LintCode Python 简单级题目 451.两两交换链表中的节点
    LintCode Python 简单级题目 174.删除链表中倒数第n个节点
    aws查看官方centos镜像imageid
    linux shell脚本查找重复行/查找非重复行/去除重复行/重复行统计
    php配置优化-生产环境应用版
  • 原文地址:https://www.cnblogs.com/wuyifu/p/3940588.html
Copyright © 2011-2022 走看看