zoukankan      html  css  js  c++  java
  • Asp.net core 2.1 Razor 的使用学习笔记(一)

    环境:vs2019 版本:16.1.1     .NET Core        ASP.NET Core 2.1    SDK 2.1.700  (20190529)

    这里说明下, Razor页面模式跟mvc出现了严重的不同。正如微软官方说的一样“Razor 页面是 ASP.NET Core MVC 的一个新功能,它可以使基于页面的编码方式更简单高效。”

    但就代码说没有什么不同几乎完全一样,但是存放的位置却有了根本的区别。个人研究分析的结果是:Razor页面模式其实是把mvc中的控制器化整为零了,即原来控制器中的操作代码被分布放到了各个页面的.cshtml.cs文件中了。这样一来由原来mvc中文件按类型分类变成了按功能分类,这样的好处就是每个页面形成了模块化,这个页面涉及的数据都在这里,便于维护,不用控制器、模型、视图来回切换了,给我的感觉多少有些像原来的web窗体的页面结构,当然化整为零后每个页面的操作不用全部去读取控制器,可能在性能有提升。

    同时,这种变化使代码功能单一,易于维护,更不易出现错误,所以还是值得一学的。 

    另外就是,因为本人经常开发一些小的项目,基本用不到sql服务,加之经常切换服务器,所以为了管理方便,数据库文件基本采用离线数据库文件(即服务器不用安装sqlserver即可使用)。如遇使用sqlserver朋友此章可以跳过,因为你不做修改,系统默认是sqlserver服务。(测试生成的数据库好像是在c盘的“文档”里?记不清了。)

    另外,因为Bootstrap V4.0.0版本正式发布了,所以我更新下这个教程,把Bootstrap的安装使用加进来。(20180222)

    一、新建项目

    1、文件》新建项目》ASP.NET Core Web应用程序

    2、依次选择“.NET Core”》“ASP.NET Core 2.1”,然后选择“Web 应用程序”(身份验证类型:个人用户账户)。

    二、修改数据库连接。引自“张不水”兄的研究成果。

    1、添加数据库

    手动在项目中添加“App_data”文件夹,并复制粘贴一个标准的内容为空的.mdf文件。为方便大家学习我这里为大家提供了示例数据库

    2、相对路径:

    修改appsettings.json文件中的"ConnectionStrings"(第3行)

    "DefaultConnection": "Data Source=(localdb)\mssqllocaldb;AttachDbFilename=%CONTENTROOTPATH%\App_Data\aspnet123.mdf;Integrated Security=True;Connect Timeout=30;MultipleActiveResultSets=true”

    需注意的是:AttachDbFilename=%CONTENTROOTPATH%\App_Data\aspnet123.mdf;

    使用 ContentRootPath 是将文件放置在项目目录下而不是wwwroot目录下,这样更安全。

    ContentRootPath 用于包含应用程序文件。
    WebRootPath 用于包含Web服务性的内容文件。
    实际使用区别如下:

    ContentRoot: C:MyApp
    WebRoot: C:MyAppwwwroot

    3、修改Startup.cs

    修改后的代码:

    ①修改Startup方法为如下

    public Startup(IConfiguration configuration,IHostingEnvironment env)
            {
                Configuration = configuration;
    //新添加 _env = env; }

    ②添加public IHostingEnvironment _env { get; }

    ③修改ConfigureServices方法

    注销掉原有的services.AddDbContext

    //添加修改()声明变量conn并做相应处理
    string conn = Configuration.GetConnectionString("DefaultConnection");
    if (conn.Contains("%CONTENTROOTPATH%"))
    {
    conn = conn.Replace("%CONTENTROOTPATH%", _env.ContentRootPath);
    }
    //修改默认的连接服务为conn
    services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(conn));

    修改完成后的代码:

    public class Startup
        {
            public Startup(IConfiguration configuration, IHostingEnvironment env)
            {
                Configuration = configuration;
                //新添加
                _env = env;
            }
    
            public IConfiguration Configuration { get; }
            //新添加
            public IHostingEnvironment _env { get; }
    
            // This method gets called by the runtime. Use this method to add services to the container.
            public void ConfigureServices(IServiceCollection services)
            {
                //services.AddDbContext<ApplicationDbContext>(options =>
                //    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    
                //添加修改()声明变量conn并做相应处理
                string conn = Configuration.GetConnectionString("DefaultConnection");
                if (conn.Contains("%CONTENTROOTPATH%"))
                {
                    conn = conn.Replace("%CONTENTROOTPATH%", _env.ContentRootPath);
                }
                //修改默认的连接服务为conn
                services.AddDbContext<ApplicationDbContext>(options =>
                          options.UseSqlServer(conn));
    
    
                services.AddIdentity<ApplicationUser, IdentityRole>()
                    .AddEntityFrameworkStores<ApplicationDbContext>()
                    .AddDefaultTokenProviders();
    
                // Add application services.
                services.AddTransient<IEmailSender, EmailSender>();
    
                services.AddMvc();
            }
    
            // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                    app.UseBrowserLink();
                    app.UseDatabaseErrorPage();
                }
                else
                {
                    app.UseExceptionHandler("/Home/Error");
                }
    
                app.UseStaticFiles();
    
                app.UseAuthentication();
    
                app.UseMvc(routes =>
                {
                    routes.MapRoute(
                        name: "default",
                        template: "{controller=Home}/{action=Index}/{id?}");
                });
            }
        }
    View Code

    三、加入Bootstrap 4.0.0.

    1、下载Bootstrap 4.0.0的预编译版本。如果你不是专业的UI设计不打算修改的话,一般来说,我们用不到源代码进行新的编译。Bootstrap4.0.0下载地址

    2、解压下载的文件并替换掉wwwroot>lib>bootstrap>dist的同名目录。(最好是先删除再复制)

    3、修改_Layout.cshtml文件。变色的地方就是修改过的地方。

    ①用下面的代码替换页面上方的:

    <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/4.0.0/css/bootstrap.min.css"
    asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"
    asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute" />

    替换原来的:

    <link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/css/bootstrap.min.css"
    asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"
    asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute" />

    ②用下面的代码替换页面下方的

    <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.slim.min.js"
    asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
    asp-fallback-test="window.jQuery"
    integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
    crossorigin="anonymous">
    </script>

    替换原来的:

    <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-2.2.0.min.js"
    asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
    asp-fallback-test="window.jQuery"
    crossorigin="anonymous"
    integrity="sha384-K+ctZQ+LL8q6tP7I94W+qzQsfRV2a+AfHIi9k8z8l9ggpc8X+Ytst4yBo/hH+8Fk">
    </script>

    ③用下面的代码替换页面下方的

    <script src="https://cdn.bootcss.com/bootstrap/4.0.0/js/bootstrap.min.js"
    asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.min.js"
    asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal"
    crossorigin="anonymous"
    integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl">
    </script>

    替换原来的:

    <script src="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/bootstrap.min.js"
    asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.min.js"
    asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal"
    crossorigin="anonymous"
    integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa">
    </script>

    四、替换文件中原来的<body>中的div内容,其实显示效果是一样的,只是用了新的Bootstrap规则来完成。

    <div class="container ">
    <nav class="navbar navbar-dark bg-dark navbar-expand-lg fixed-top">
    <a class="navbar-brand" href="#">项目名称</a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
    </button>
    <div class="navbar-collapse collapse" id="navbarSupportedContent">
    <ul class="navbar-nav mr-auto">
    <li class="nav-item active"><a  asp-page="/Index" class="nav-link">Home</a></li>
    <li class="nav-item"><a asp-page="/About" class="nav-link">About</a></li>
    <li class="nav-item"><a asp-page="/Contact" class="nav-link">Contact</a></li>
    </ul>
    @await Html.PartialAsync("_LoginPartial")
    </div>
    </nav>
    </div>
    <div class="container body-content">
    @RenderBody()
    <hr />
    <footer>
    <p>&copy; 2017 - </p>
    </footer>
    </div>

    五、修改Index.cshtml文件。这里主要是Carousel控件需要部分修改

    这是修改好了的代码:

    <div id="myCarousel" class="carousel slide" data-ride="carousel" data-interval="6000">
    <ol class="carousel-indicators">
    <li data-target="#myCarousel" data-slide-to="0" class="active"></li>
    <li data-target="#myCarousel" data-slide-to="1"></li>
    <li data-target="#myCarousel" data-slide-to="2"></li>
    <li data-target="#myCarousel" data-slide-to="3"></li>
    </ol>
    <div class="carousel-inner">
    <div class="carousel-item active">
    <img class="w-100" src="~/images/banner1.svg" alt="ASP.NET"/>
    <div class="carousel-caption d-none d-md-block">
    <p>
    Learn how to build ASP.NET apps that can run anywhere.
    <a class="btn btn-default" href="https://go.microsoft.com/fwlink/?LinkID=525028&clcid=0x409">
    Learn More
    </a>
    </p>
    </div>
    </div>
    <div class="carousel-item">
    <img class="w-100" src="~/images/banner2.svg" alt="Visual Studio"/>
    <div class="carousel-caption d-none d-md-block">
    <p>
    There are powerful new features in Visual Studio for building modern web apps.
    <a class="btn btn-default" href="https://go.microsoft.com/fwlink/?LinkID=525030&clcid=0x409">
    Learn More
    </a>
    </p>
    </div>
    </div>
    <div class="carousel-item">
    <img class="w-100" src="~/images/banner3.svg" alt="Package Management"/>
    <div class="carousel-caption d-none d-md-block">
    <p>
    Bring in libraries from NuGet and npm, and automate tasks using Grunt or Gulp.
    <a class="btn btn-default" href="https://go.microsoft.com/fwlink/?LinkID=525029&clcid=0x409">
    Learn More
    </a>
    </p>
    </div>
    </div>
    <div class="carousel-item">
    <img class="w-100" src="~/images/banner4.svg" alt="Microsoft Azure"/>
    <div class="carousel-caption d-none d-md-block">
    <p>
    Learn how Microsoft's Azure cloud platform allows you to build, deploy, and scale web apps.
    <a class="btn btn-default" href="https://go.microsoft.com/fwlink/?LinkID=525027&clcid=0x409">
    Learn More
    </a>
    </p>
    </div>
    </div>
    </div>
    <a class="carousel-control-prev" href="#myCarousel" role="button" data-slide="prev">
    <span class="carousel-control-prev-icon" aria-hidden="true"></span>
    <span class="sr-only">Previous</span>
    </a>
    <a class="carousel-control-next" href="#myCarousel" role="button" data-slide="next">
    <span class="carousel-control-next-icon" aria-hidden="true"></span>
    <span class="sr-only">Next</span>
    </a>
    </div>

    六、修改_LoginPartial.cshtml文件。主要就是去掉<ul>class里面的nav,在<li>里添加class="nav-item"

    改后如下:

    @if (SignInManager.IsSignedIn(User))
    {
    <form asp-controller="Account" asp-action="Logout" method="post" id="logoutForm" class="navbar-right">
    <ul class="navbar-nav navbar-right">
    <li class="nav-item">
    <a asp-page="/Account/Manage/Index" title="Manage" class="nav-link">Hello @UserManager.GetUserName(User)!</a>
    </li>
    <li class="nav-item">
    <button type="submit" class="btn btn-link  nav-link">Log out</button>
    </li>
    </ul>
    </form>
    }
    else
    {
    <ul class="navbar-nav">
    <li class="nav-item"><a asp-page="/Account/Register" class="nav-link">Register</a></li>
    <li class="nav-item"><a asp-page="/Account/Login" class="nav-link">Log in</a></li>
    </ul>
    }

    编译后,你会得到和原来一模一样的界面。Bootstrap V4.0.0 确实比原来有进步,差异还不小。具体请参考相关资料,对于研究过bootstrap的朋友来说,还是很简单的。个人觉得比3.3.7好用了。

  • 相关阅读:
    Two Sum II
    Subarray Sum
    Intersection of Two Arrays
    Reorder List
    Convert Sorted List to Binary Search Tree
    Remove Duplicates from Sorted List II
    Partition List
    Linked List Cycle II
    Sort List
    struts2结果跳转和参数获取
  • 原文地址:https://www.cnblogs.com/chonghanyu/p/8400214.html
Copyright © 2011-2022 走看看