MVC01

1.Controller

1) 添加:

在Controller目录右键进行添加,出现很多模式供选择,选择空的Controller,命名后新建。新建后Views

目录将同步生成相应名称的视图文件目录

均继承于Controller类

控制器内的方法默认返回ActionResultl类型,可自行修改

修改后可运行并在域名后加入自动生成的Views目录下的文件名称,就可以访问到该路由

该路由通过/Hello访问

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 string Index()
        {
            return "Hello MVC";
        }
    }
}

也可以新建自己的方法(路由):该路由通过/Hello/Yes访问

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 string Index()
        {
            return "Hello MVC";
        }

        public string Yes()
        {
            return "Yse MVC, this is Yes.";
        }
    }
}

如果要进行url传参,就为上述方法添加参数

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 string Index()
        {
            return "Hello MVC";
        }

        public string Yes(string name)
        {
            return "Yse MVC, this is Yes." + name;

        }
    }
}

但这么做比较不安全

通常接收用户传参时我们先进行一个编码:

也可为传参添加缺省值

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 string Index()
        {
            return "Hello MVC";
        }

        // 参数缺省值
        public string Yes(string name = "Linda")
        {
            return "Yse MVC, this is Yes." + HttpUtility.HtmlEncode(name);
            //或 return "Yse MVC, this is Yes." + Server.HtmlEncode(name);


        }
    }
}

小技巧:F5键 Debug模式,执行断点

ctrl+F5 Debug模式但不执行断点

测试时将为我们使用IIS搭建一个建议的服务器

Global.asax文件可以查看路由的一些配置

RegisterRoutes方法

2)调试技巧:

原文地址:https://www.cnblogs.com/Tanqurey/p/12189774.html