ASP.NET MVC 入门教程
由于网上的关于ASP.NET 相关的教程并不是很多,因此做这一期文章来教大家入门
提示:在读这篇文章之前需要有一定的MVC基础
文章目录
创建ASP.NET
Controller层的类对应View中的每个文件夹,Controller类中的方法对应View中文件夹中的类
执行流程
- 当我们访问/Home/about的时候,执行流程如下
公共模板布局
- About.cshtml
@{ ViewBag.Title = "About";//ViewBag为Controller 链接View的数据域 } <h2>@ViewBag.Title.</h2> <h3>@ViewBag.Message</h3> <p>Use this area to provide additional information.</p>
可以看到代码并没有写导航栏和底部栏,这是因为用了公共模板,普通view会渲染到@RenderBody()中
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title - 我的 ASP.NET 应用程序</title>
@*根据BundleConfig.cs的绑定规则,自动加载content中的静态文件*@
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
@Html.ActionLink("应用程序名称", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>@Html.ActionLink("主页", "Index", "Home")</li>
<li>@Html.ActionLink("关于", "About", "Home")</li>
<li>@Html.ActionLink("联系方式", "Contact", "Home")</li>
</ul>
</div>
</div>
</div>
<div class="container body-content">
@*其他的controller会默认渲染到这里*@
@RenderBody()
<hr />
<footer>
<p>© @DateTime.Now.Year - 我的 ASP.NET 应用程序</p>
</footer>
</div>
@*根据BundleConfig.cs的绑定规则,自动加载content中的静态文件*@
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
</body>
</html>
-
如不需要公共模板可以加
@{ ViewBag.Title = "Index"; Layout = null;//不使用默认的布局 }
获取请求参数值
- 前端
GET参数
-
HelloController.cs
// GET: Hello public ActionResult Index() { //获取get请求中的参数 return Content($"{Request.QueryString["name"]}-{Request.QueryString["age"]}"); }
结合前端看注释
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace ASP.NET20240813.Controllers
{
public class HelloController : Controller
{
// GET: Hello
public ActionResult Index()
{
//获取get请求中的参数
return Content($"{Request.QueryString["name"]}-{Request.QueryString["age"]}");
}
[HttpPost]
public ActionResult PostData()
{
//获取post请求中的参数
return Content($"{Request.Form["LoginName"]}");
}
/// <summary>
/// 文件上传
/// </summary>
/// <returns></returns>
public ActionResult FileUpload()
{
//文件上传,上传到本地项目的upload目录下
//saveAs方法需要根路径,所有我们需要将相对路径转换成绝对路径
var absolutePath = Request.MapPath("~/upload/");
Request.Files["file"].SaveAs(absolutePath + Request.Files["file"].FileName);
//重定向
Response.Redirect("http://www.baidu.com");
return Content("成功");
}
/// <summary>
/// cookie,session clear/abandon
/// 创建session
/// 创建cookie并设置有效期
/// </summary>
/// <returns></returns>
public ActionResult CSEg()
{
//创建session
Session["user"] = Request.QueryString["username"];
//创建cookie
Response.Cookies.Add(new HttpCookie("userCookie")
{
Value = "abc123",
Expires = DateTime.Now.AddDays(7)
}); ;
return Content("设置成功");
}
/// <summary>
/// cookie 和 session的销毁
/// </summary>
/// <returns></returns>
public ActionResult CSDelete()
{
string msg = Request.Cookies["userCookie"].Value;
//消除cookie
Response.Cookies.Add(new HttpCookie("userCookie")
{
Expires = DateTime.Now.AddDays(-1)
}); ;
Session.Abandon();
return Content(msg.ToString());
}
}
}
传递数据
ViewBag ViewData TempData View 这几个都差不多,在服务端保存数据,可传递到视图层访问
-
ViewBag
/// <summary> /// ViewData本质是ViewBag,所以可以ViewBag.name访问 /// </summary> /// <returns></returns> public ActionResult ViewBagAndViewData() { ViewBag.Phone = 1343433; ViewData["name"] = "张三"; return View(); }
@{ ViewBag.Title = "ViewBagAndViewData"; } <h2>ViewBagAndViewData</h2> @*访问方式*@ <h1>@ViewBag.name</h1> <h1>@ViewBag.Phone</h1>
View传递
View()重载了很多方法,可以传入实体,视图,模板配置等等,这里举例一下实体model,通常传入实体的时候,视图层是不会提示的,需要指定model类型@model ASP.NET20240813.Models.Stu
/// <summary>
/// 视图层,使用@Model访问对象数据
/// View有多个重载方法,可以指定视图,模板.....
/// </summary>
/// <returns></returns>
public ActionResult ViewExp()
{
return View(new Stu()
{
Name = "张三",
Age=12
});
}
@model ASP.NET20240813.Models.Stu
@*会有提示,表明传来的对象类型是什么*@
@{
ViewBag.Title = "ViewExp";
}
<h2>ViewExp</h2>
<h1>@Model.Age @Model.Name</h1>
登录校验案例
model校验
-
可以在model属性添加约束条件,这样方便消除视图编写js等冗余逻辑
namespace ASP.NET20240813.Models { public class LoginModel { /// <summary> /// 我们只需要在这上面添加校验,视图层即可改变和约束 /// </summary> [Display(Name ="电子邮箱")] [Required,StringLength(10,MinimumLength =2)] [DataType(DataType.Password)] public string Email { get; set; } } }
编写controller
-
视图展示和逻辑通常成对存在
/// <summary> /// 返回视图的 /// 通常和逻辑的是配套的 /// </summary> /// <returns></returns> [HttpGet] public ActionResult Login() { return View(); } /// <summary> /// 处理逻辑的 /// 使用模型校验可以选择相应的模板,生成校验视图 /// </summary> /// <param name="model"></param> /// <returns></returns> [HttpPost] public ActionResult Login(LoginModel model) { //模型校验 if (ModelState.IsValid) { if (model.Email.Equals("123")) { return Content("yes"); } else { return Content("no"); } } return Content("校验不成功"); }
通过地址访问,走的是返回视图,返回一个页面,当点击登录,走的是处理逻辑的接口
效果
返回
常见返回
View:返回视图,RedirectToAction,Redirect:重定向,Content:返回字符串,File:返回图片
-
RedirectToAction可指定的controller中的哪个action
public ActionResult ReRouteTest() { //第一个:action 第二个:指定controller return RedirectToAction("Index", "Home"); }
-
File指定路径和类型即可返回
public ActionResult GetFile(string file) { //返回一张图片 return File($@"~/upload/{file}","image/jpeg"); }
返回JSON
/// <summary>
/// 返回json
/// </summary>
/// <returns></returns>
public ActionResult GetJson()
{
return Json(new { id=1, name = "张三" },JsonRequestBehavior.AllowGet);
}
PartialView
-
用于在视图中嵌入或重用小的、独立的视图片段。PartialView通常用于显示重复的UI元素,如导航菜单、页脚、侧边栏、表单元素等
-
局部:需在controller层和视图层指定