• 第3章 ASP.NET MVC(视图)


    视图

    一、      理解视图的渲染

    视图的生成和显示

    二、      配置视图的搜索位置

    1、         视图的搜索规则

    2、         改变视图的的搜索 规则

    1)         自定义视图引擎

    2)         注册自定义视图引擎

    三、      视图中调用类的方法

    四、      使用HTML辅助器

    1、         在视图中定义方法

    只能在当前视图中使用

    2、         定义扩展方法

    可以在所有视图中使用

    1)         定义静态类,名称不是很重要

    2)         定义静态的扩展方法

    A、        返回类型MvcHtmlString

    B、        扩展的方法(this HtmlHelprt html,参数)

    C、        使用TagBulder 创建标签

    3)         视图中使用

    在Views文件夹下的wed.config中注册使用@Html.方法名(参数)调用

    五、      使用内置的HTML Helper方法

    1、         创建表单

    2、         使用inputHelper

    3、         使用强类型的Helpers方法

    4、         创建Select元素

    5、         创建链接和

    六、      分布视图

    1、         创建分布视图

    2、         分部视图在主视图显示

    3、         分部视图与主视图数据共享

    七、      子动作

    八、      使用WebGrid Helper

    结合第2章内容,完善分类功能

    一、先在“Content”文件里面“Product.css”样式里面添加一行代码

    如图所示:

    代码示例:

    body {font-family:Cambria,Georgia,"Times New Roman";margin:0;}
    div#header div.title, div.item h3, div.item h4, div.pager a {
        font:bold 1em "Arial Narrow","Franklin Gothic Medium",Arial;
    }
    div#header {
        background-color:#444;border-bottom:2px solid #111;color:white;
    }
        div#header div.title {
            font-size:1.2em;padding:.5em;
        }
    div#content {
        border-left:2px solid gray;margin-left:13em;padding:1em;
    }
    div#categories {
        float:left;width:12em;padding:.3em;
    }
    div.item {
        border-top:1px dotted gray;padding-top:.7em;margin-bottom:.7em;
    }
        div.item:first-child {
            border-top:none;padding-top:0;
        }
    
        div.item h3 {
            font-size:1.3em;margin:0 0 .25em 0;
        }
        div.item h4 {
            font-size:1.1em;margin:.4em 0 0 0;
        }
    
    div.pager {
        text-align:right;border-top:0px solid silver;
        padding:.5em 0 0 0;margin-top:1em;
    }
        div.pager a {
            font-size:1.1em;color:#666;text-decoration:none;
            padding:0 .4em 0 .4em;
        }
            div.pager a:hover {
                background-color:silver;
            }
            div.pager a.selected {
                background-color:#353535;color:white;
            }
    div#categories a {
        font:bold 1.1em "Arial Narrow","Franklin Gothic Medium",Arial;
        display:block;
        text-decoration:none;padding:.6em;color:black;
        border-bottom:1px solid silver;
    }
        div#categories a.selected {
            background-color:#666;color:white;
        }
        div#categories a:hover {
            background-color:#ccc;
        }
        div#categories a.selected:hover {
            background-color:#666;
        }
    div#left {
        float:left;
        height:160px;width:140px;border:0px solid #00ff00;
    }
    
    .clearfix {
        *zoom: 1
    }
    .clearfix:before,
    .clearfix:after {
        content: " ";
        display: table
    }
    
    .clearfix:after {
        clear: both
    }
    .warp 
    {
        width:1143.02px;
        height:160px;
    }
    View Code

     二、修改视图(Shared)里面主界面(_Layout.cshtml)代码

    如图所示:

    代码示例:

    <!DOCTYPE html>
    <html>
    <head>
        <title>@ViewBag.Title</title>
          <link href="@Url.Content("~/Content/Product.css")" rel="stylesheet" type="text/css" />
        <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
        <script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
    </head>
    <body>
        <div class="page">
            <div id="header">
                <div id="title">
                    <h1>在线体育产品</h1>
                </div>
                <div id="logindisplay">
                    @Html.Partial("_LogOnPartial")
                </div>
                <div id="menucontainer">
                    <ul id="menu">
                        <li>@Html.ActionLink("主页", "Index", "Home")</li>
                         <li>@Html.ActionLink("产品", "List", "Home")</li>
                        <li>@Html.ActionLink("关于", "About", "Home")</li>
                    </ul>
                </div>
            </div>
    
            <div id="main">
                <div id="categories">
    
                </div>
               <div id="content">
                    @RenderBody()
               </div>
            </div>
        </div>
    </body>
    </html>
    View Code

    效果:会出现一条垂直线分来分类

    三、完成后,来到业务"逻辑层"编程获取数据分类方法

    如图所示:

    代码示例:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    using LinqService;  //引用
    namespace LinqBLL
    {
        public class ProductBll
        {
            public List<Product> GetProduct()
            {
                using (SportsStoreEntities se = new SportsStoreEntities())
                {
                    var products = se.Product;  //数据库里面表名称
                    return products.ToList();
                }
            }
            //通过分类名获取体育产品列表
            public List<Product> GetProductByCateName(string cate)
            {
                using(SportsStoreEntities se=new SportsStoreEntities())
                {
                    if (string.IsNullOrEmpty(cate))
                    { 
                        var products=se.Product;
                        return products.ToList();
                    }
                      else  //查找对应分类数据
                    {
                        var books = from a in se.Product                           
                                    where a.Name.Contains(cate)
                                    select a;
                        return books.ToList();
                    }
                }
            }
            //获取分类名称集
            public IEnumerable<string> GetCategories()
            {
                var se = new SportsStoreEntities();
                var s = from a in se.Product
                        select new { a.Category };
                //Distinct:去掉重复分类名,OrderBy:升序
                return s.Select(x => x.Category).Distinct().OrderBy(x => x);
            }
        }
    }
    View Code

    四、来到“Controller”文件添加一个控制器名为"NavContoller"

    如图所示:

    五、调用“业务逻辑层”方法

    如图所示:

     

    代码示例:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    
    using LinqBLL;
    namespace MvcProduct.Controllers
    {
        public class NavController : Controller
        {
            //
            // GET: /Nav/
            // cate=null:没有取空值
            //菜单的分布视图
            public PartialViewResult Menu(string cate=null)
            {
                ProductBll bll = new ProductBll();
                //设置选中分类
                ViewBag.SelectCategroies = cate;
                return PartialView(bll.GetCategories());
            }
    
        }
    }
    View Code

     六、在"Menu"方法单击右键选择“添加视图”为“分布视图”

    如图所示:

     

    七、编程"Menu"分布视图,也就是"后台数据"加载到左侧栏并实现分类功能

    如图所示:

    代码示例:

    @model IEnumerable<string>
               @{
                   Layout = null;   
                }
    @Html.ActionLink("首页", "Index", "Home");
    @foreach (var link in Model)
    {
        @Html.RouteLink(link, new { controller = "Home", action = "List", cate = link },
        new {@controller=link==ViewBag.SelectCategroy?"selected":null })
    }
    View Code

     八、来到主界面(_Layout.cshtml)调用该方法

    如图所示:

     

    到这里运行效果:

    九、实现分类功能后,现在实现分页效果:先在"Models"文件添加两个类 一个类名为"PagingInfo",另一类名"ProducrsListViewModel"

    如图所示:(PagingInfo类)

    如图所示:(ProducrsListViewModel类)

    代码案例:(PagingInfo类)

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace MvcProduct.Models
    {
        //分类
        public class PagingInfo
        {
            //总记录
            public int RecordCount { get; set; }
            //每页显示记录数
            public int PageSize { get; set; }
            //当前页数索引
            public int CurrentIndex { get; set; }
            //总页数
            public int pageCount 
            {
                get { return (int)Math.Ceiling((decimal)RecordCount / PageSize); }
            }
        }
    }
    View Code

    代码示例(ProducrsListViewModel类)

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    using LinqService;
    namespace MvcProduct.Models
    {
        //产品列表视图模型类
        public class ProducrsListViewModel
        {
            public IEnumerable<Product> Producrs { get; set; }
            public PagingInfo PagingInfo { get; set; }
            public string CurrentCategory { get; set; }
        }
    }
    View Code

    十、在MvcProduct项目上添加一个文件夹名为"HtmlHelper",然后再添加一个类名为“pagingHelper”

    并写上"方法"且把方法改为"静态",记得引入命名空间

    如图所示:

     

    代码示例:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    using MvcProduct.Models;
    using System.Web.Mvc;
    using System.Text;
    namespace MvcProduct.HtmlHelper
    {
        public static class pagingHelper
        {
            public static MvcHtmlString PageLinks(this System.Web.Mvc.HtmlHelper html,
                PagingInfo pagingInfo, Func<int, string> pageUrl)
            {
                StringBuilder result = new StringBuilder();
                //遍历所有页数
                for (int i = 1; i < pagingInfo.RecordCount; i++)
                {
                    TagBuilder tag = new TagBuilder("a"); //创建链接标签
                    tag.MergeAttribute("href", pageUrl(i));
                    tag.InnerHtml = i.ToString();
                    //给当前页数添加样式
                    if (i == pagingInfo.CurrentIndex)
                        tag.AddCssClass("selected");
                    result.Append(tag.ToString());
                }
                return new MvcHtmlString(result.ToString());
            }
        }
    }
    View Code

    十一、然后来到“业务逻辑层”完善"分类列表"方法并添加一个"获取所有页数"方法

    如图所示:(完善分类列表)

    如图所示:(添加获取所有页数)

    代码示例:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    using LinqService;  //引用
    namespace LinqBLL
    {
        public class ProductBll
        {
            public List<Product> GetProduct()
            {
                using (SportsStoreEntities se = new SportsStoreEntities())
                {
                    var products = se.Product;  //数据库里面表名称
                    return products.ToList();
                }
            }
            //通过分类名获取体育产品列表
            public List<Product> GetProductByCateName(string cate,int stIndex,int count)
            {
                using(SportsStoreEntities se=new SportsStoreEntities())
                {
                    if (string.IsNullOrEmpty(cate))  //查找所有
                    { 
                        var products=se.Product.OrderBy(x=>x.ProductID).Skip(stIndex).Take(count);
                        return products.ToList();
                    }
                      else  //查找对应分类数据
                    {
                        var books = from a in se.Product                           
                                    where a.Category.Contains(cate)
                                    select a;
                        return books.OrderBy(x=>x.ProductID).Skip(stIndex).Take(count).ToList();
                    }
                }
            }
            //获取所有记录数
            public int GetRecordCount(string cate)
            {
                using (SportsStoreEntities se = new SportsStoreEntities())
                {
                    if (string.IsNullOrEmpty(cate))  //查找所有
                    {                
                        return se.Product.Count();
                    }
                    else  //查找对应分类数据
                    {
                        var books = from a in se.Product
                                    where a.Category.Contains(cate)
                                    select a;
                        return books.Count();
                    }
                }
            }
            //获取分类名称集
            public IEnumerable<string> GetCategories()
            {
                var se = new SportsStoreEntities();
                var s = from a in se.Product
                        select new { a.Category };
                //Distinct:去掉重复分类名,OrderBy:升序
                return s.Select(x => x.Category).Distinct().OrderBy(x => x);
            }
        }
    }
    View Code

    十二、在"Controller"文件完善"HomeController.cs"代码

    如图所示:

     

    代码示例:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    
    using LinqBLL;
    using LinqService;
    using MvcProduct.Models;
    namespace MvcProduct.Controllers
    {
        public class HomeController : Controller
        {
            ProductBll bll = new ProductBll();
            public ActionResult Index()
            {
                ViewBag.Message = "欢迎使用 ASP.NET MVC!";
                return View();
            }
            ////获取产品
            //public ActionResult List() 
            //{
            //    List<Product> ps = bll.GetProduct();
            //    return View(ps);
            //}
            public ActionResult List(string cate,int page=1)
            {
                ProductBll ps = new ProductBll();
                int pageSize = 4;  //设置记录条数
                //获取总记录数
                int recordCount = bll.GetRecordCount(cate);
                //获取数据
                List<Product> lst = bll.GetProductByCateName(cate,
                    (page - 1) * pageSize, pageSize);
    
                ProducrsListViewModel ViewModel = new ProducrsListViewModel
                {
                    Producrs = lst, //设置数据
                    PagingInfo = new PagingInfo   //设置分页参数
                    {
                        CurrentIndex=page,
                        PageSize=pageSize,
                        RecordCount=recordCount
                    },
                    CurrentCategory=cate    //设置分类
                };
                return View(ViewModel);
            }
            public ActionResult About()
            {
                return View();
            }
        }
    }
    View Code

     十三、在这里先设置全局引用,减少代码冗余

    如图所示:

    十四、完善"视图"里面“List”方法

    如图所示:(上部分)

    如图所示;(下部分)

     

    代码示例:

    @model MvcProduct.Models.ProducrsListViewModel
    
    @{
        ViewBag.Title = "List";
    }
    
    <h2>体育产品</h2>
    
    
        @foreach (var p in Model.Producrs)
        {
           <div class="warp clearfix">
             <div id="left">
               <img alt="@p.Name" src="../../@p.Image" width="135px" height="155px" border="0" />
              </div> 
                 <div class="item">
                  <h3>@p.nDescription</h3><br />                   
                      @p.Category                     
                  <h4>@string.Format("{0:F}",p.Price)</h4><br />                  
                     <input type="submit" value="加入购物车" />
                    </div>
                     </div>
                   <hr  style="border-style:inset"/>        
        }
    <div class="pager">
        @Html.PageLinks(Model.PagingInfo, x => Url.Action("List", new {page=x,cate=Model.CurrentCategory }))
    </div>
    View Code

     十三、到这里,基本完成了,为了防止转义字符错误,最好到"Web.config"添加一行代码

    如图所示:

    代码示例:

    <?xml version="1.0" encoding="utf-8"?>
    <!--
      有关如何配置 ASP.NET 应用程序的详细信息,请访问
      http://go.microsoft.com/fwlink/?LinkId=152368
      -->
    <configuration>
      <configSections>
        <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
        <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
      </configSections>
      <appSettings>
        <add key="webpages:Version" value="1.0.0.0" />
        <add key="ClientValidationEnabled" value="true" />
        <add key="UnobtrusiveJavaScriptEnabled" value="true" />
      </appSettings>
      <system.web>
        <compilation debug="true" targetFramework="4.0" />
        <authentication mode="Forms">
          <forms loginUrl="~/Account/LogOn" timeout="2880" />
        </authentication>
        <pages>
          <namespaces>
            <add namespace="System.Web.Helpers" />
            <add namespace="System.Web.Mvc" />
            <add namespace="System.Web.Mvc.Ajax" />
            <add namespace="System.Web.Mvc.Html" />
            <add namespace="System.Web.Routing" />
            <add namespace="System.Web.WebPages" />
          </namespaces>
        </pages>
        <profile defaultProvider="DefaultProfileProvider">
          <providers>
            <add name="DefaultProfileProvider" type="System.Web.Providers.DefaultProfileProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
          </providers>
        </profile>
        <membership defaultProvider="DefaultMembershipProvider">
          <providers>
            <add name="DefaultMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
          </providers>
        </membership>
        <roleManager defaultProvider="DefaultRoleProvider">
          <providers>
            <add name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
          </providers>
        </roleManager>
        <!--
                If you are deploying to a cloud environment that has multiple web server instances,
                you should change session state mode from "InProc" to "Custom". In addition,
                change the connection string named "DefaultConnection" to connect to an instance
                of SQL Server (including SQL Azure and SQL  Compact) instead of to SQL Server Express.
          -->
        <sessionState mode="InProc" customProvider="DefaultSessionProvider">
          <providers>
            <add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" />
          </providers>
        </sessionState>
      </system.web>
      <system.webServer>
    
        <!--解决转义字符-->
        <security>
          <requestFiltering allowDoubleEscaping="true"></requestFiltering>
        </security>
        
        <validation validateIntegratedModeConfiguration="false" />
        <modules runAllManagedModulesForAllRequests="true" />
      </system.webServer>
      <runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
          <dependentAssembly>
            <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" />
          </dependentAssembly>
        </assemblyBinding>
      </runtime>
      <entityFramework>
        <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
          <parameters>
            <parameter value="v11.0" />
          </parameters>
        </defaultConnectionFactory>
      </entityFramework>
      <!--<connectionStrings>
        <add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDb)v11.0;Initial Catalog=aspnet-MvcProduct-20170103151428;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnet-MvcProduct-20170103151428.mdf" />
      </connectionStrings>-->
      <connectionStrings>
        <add name="SportsStoreEntities" connectionString="metadata=res://*/Product.csdl|res://*/Product.ssdl|res://*/Product.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=.;initial catalog=SportsStore;user id=sa;password=sa;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
      </connectionStrings>
    </configuration>
    View Code

    运行结果:

     十四、由于页数太多,一下加载数字太多,所以在这里完善页数显示效果,找到"pagingHelper.cs"页面完善代码

    如图所示:(上部分)

    如图所示:(下部分)

    代码示例:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    using MvcProduct.Models;
    using System.Web.Mvc;
    using System.Text;
    namespace MvcProduct.HtmlHelper
    {
        public static class pagingHelper
        {
            public static MvcHtmlString PageLinks(this System.Web.Mvc.HtmlHelper html,
                PagingInfo pagingInfo, Func<int, string> pageUrl)
            {
                StringBuilder result = new StringBuilder();
                int page = pagingInfo.CurrentIndex;   //CurrentIndex:当前页数索引
                const int len = 7;
                int stIndex = 1;
                int endIndex=pagingInfo.pageCount;  //pageCount:总页数
    
                if (pagingInfo.pageCount <= 15)
                {
                    endIndex = pagingInfo.pageCount;
                }
                else
                {
                    if (pagingInfo.CurrentIndex > len)
                    {
                        if (pagingInfo.CurrentIndex + len > pagingInfo.pageCount)
                        {
                            stIndex = pagingInfo.pageCount - len * 2;
                            endIndex = pagingInfo.pageCount;
                        }
                        else
                        {
                            stIndex = pagingInfo.CurrentIndex - len;
                            endIndex = pagingInfo.CurrentIndex +len;
                        }
                    }
                    else
                    {
                        stIndex = 1;
                        endIndex = 15;
                    }
                }
                //遍历所有页数
                for (int i = stIndex; i <=endIndex; i++)
                {
                    TagBuilder tag = new TagBuilder("a"); //创建链接标签
                    tag.MergeAttribute("href", pageUrl(i));
                    tag.InnerHtml = i.ToString();
                    //给当前页数添加样式
                    if (i == pagingInfo.CurrentIndex)
                        tag.AddCssClass("selected");
                    result.Append(tag.ToString());
                }
                return new MvcHtmlString(result.ToString());
            }
        }
    }
    View Code

    最终运行效果:

  • 相关阅读:
    PHP preg_replace_callback_array() 函数
    PHP preg_quote() 函数
    PHP preg_match() 函数
    SqlHelper工具类
    ArrayListd的长度问题
    事务
    Socket通信
    时间戳,产生随机数
    背景大小 | background-size (Backgrounds & Borders)
    背景图片位置 | background-position (Backgrounds & Borders)
  • 原文地址:https://www.cnblogs.com/xuyangyang/p/6272704.html
Copyright © 2020-2023  润新知