zoukankan      html  css  js  c++  java
  • MVC02

    1. 添加View

    1)在添加完Controller生成的View目录右键新建,添加名称,选择模板,

    下边可以选择一个Layout布局页,选择shared共享的布局

    2) 在之前的路由中为我们直接返回的是字符串,这次把类型改回为原来的

    ActionResult,并返回View()方法,View方法会直接找到View下面的相应视图进行呈现

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    
    namespace HelloMVC.Controllers
    {
        public class HelloController : Controller
        {
            // GET: Hello
            public ActionResult Index()
            {
                return View();
            }
    
            // 参数缺省值
            public string Yes(string name = "Linda")
            {
                return "Yse MVC, this is Yes." + HttpUtility.HtmlEncode(name);
                //或 return "Yse MVC, this is Yes." + Server.HtmlEncode(name);
    
    
            }
        }
    }

    右键cshtml文件,view in page inspector 

    这样方便程序员进行网页开发。

    为什么ASP.NET可以在html文件中插入C#语句?因为他借助了Razor引擎

    在cshtml内声明一个变量:

    @{var a = 100;}

    或者inlline内联调用

    @{
        ViewBag.Title = "Index";
        Layout = "~/Views/Shared/_Layout.cshtml";
    }
    
    <h2>Index</h2>
    
    <p>这是Hello的首页,欢迎光临</p>
    
    @{var a = 100;}
    <p>the value of a is @a</p>

    可以直接调用服务器上的一些代码

    使用/**/进行注释

    3)我们没有为上面的cshtml文件添加banner,那么是从何加上的模板呢

    主要是我们引用了shaerd目录下的

    @{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
    }

    在上述的Layout文件中,

    container body-content类将包括上述的嵌入体内容

    4)从controller向view传递数据

    因为我们不提倡在view内进行逻辑处理以及数据库交互,

    我们借助ViewBag进行传递

    Controller部分:

            public ActionResult Yes(string name = "Linda",int numTimes = 1)
            {
                ViewBag.Message = "hello," + name;
                ViewBag.NumTimes = numTimes;
                return View();
            }

    View部分

    @{
        ViewBag.Title = "Welcome";
        Layout = "~/Views/Shared/_Layout.cshtml";
    }
    
    <h2>Yes Page</h2>
    <p>下面呈现Controller传来的数据</p>
    <ul>
        @for(int i = 0; i < ViewBag.NumTimes; i++)
        {
            <li>@ViewBag.Message</li>
        }
    </ul>
  • 相关阅读:
    CodeForces 734F Anton and School
    CodeForces 733F Drivers Dissatisfaction
    CodeForces 733C Epidemic in Monstropolis
    ZOJ 3498 Javabeans
    ZOJ 3497 Mistwald
    ZOJ 3495 Lego Bricks
    CodeForces 732F Tourist Reform
    CodeForces 732E Sockets
    CodeForces 731E Funny Game
    CodeForces 731D 80-th Level Archeology
  • 原文地址:https://www.cnblogs.com/Tanqurey/p/12202815.html
Copyright © 2011-2022 走看看