二:第一个MVC应用程序

创建MVC项目

1:File->New->Project->New Project

选择Visual C#中Web模板中的ASP.NET Web Application定义

2:添加控制器

在Controller文件夹中右键选择Add->Controller

把新建的控制器名修改为HomeController

3:修改HomeController中的内容

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Pro2.Controllers
{
    public class HomeController : Controller
    {
        public string Index()
        {
            return "Hello World!";
        }
    }
}

4:运行该项目可以看到浏览器结果

可以看到浏览器的地址是http://localhost:xxxx,其中xxxx是IIS Express随机分配的端口

初步理解路由

MVC项目的路由系统(Routing System)会解析请求的URL,

路由系统会把http://localhost:xxxx,http://localhost:xxxx/Home,http://localhost:xxxx/Home/Index都指向HomeController中的Index方法

第一个视图(View)

5:修改HomeController方法的代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Pro2.Controllers
{
    public class HomeController : Controller
    {
        public ViewResult Index()
        {
            return View();
        }
    }
}

6:右键Index()方法,Add View

默认View的名字为Index,这里不要修改Index名,否则系统会识别不到该View

点击确认

7:修改View,打开Views/Home/Index.cshtml文件,修改为如下

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div> 
        Hello World(from view)
    </div>
</body>
</html>

8:编译并运行项目

正常情况会得到正确的结果,如果我本地出现了下面错误

9:修改Reference属性

找到Reference中的System.Web.MVC修改属性Copy Local为True

10:再次运行该项目得到正确结果

说明

1:IIS Express是一个精简版的全功能的IIS应用服务器,由Visual Studio调用,用于开发调试和使用;

2:Web页面从服务器到客户端浏览器分三步,第一步是视图引擎对视图文件进行解释,转换成Html标记,称为渲染。第二步把渲染后的Html传递给客户端浏览器,称为传输。第三步是浏览器把Html解析处理并呈现Web页面,称为呈现。

猜你喜欢

转载自www.cnblogs.com/yuanhaowen/p/9851694.html