ASP.NET + MVC5 入门完整教程三 (上) --- 第一个 MVC 项目_lingshuangcanxue-CSDN 博客_asp.net mvc
第一个 MVC 应用程序
1 创建 MVC 项目
打开 VS ,File-- 新建 -- 项目,选择 ASP Web 项目,命名后确认。选择(Empty)空模板,
项目创建完成,会看到 解决方案管理器 窗口显示一些文件夹,如图,这是一个 MVC 的默认结构
2 添加第一个控制器
右键 解决方案中的 “Controllers” 文件夹,从弹出菜单选择 “添加”->“控制器”如上图所示;
添加后出现下图,单击 “Add(添加)” 按钮
这是打开 控制器对话框,命名为 “Home Controller”,点击添加。
VS 会在 Controllers 文件夹下创建一个新的 C# 文件,名称为 "Home Controller.cs",这个类如下图所示;
3 渲染 Web 界面
创建 web 界面,在 Index 界面任意地方右键,从弹出菜单选择 “Add View(添加视图)”,如下图:
Index.cshtml 基本内容如下所示:
我们看到:
@{
Layout = null;
}
这是一个将由 Razor 视图引擎进行解释的表达式,Razor 引擎处理视图内容并生成发送给浏览器的 HTML。这是一个简单的 Razor 表达式,他告诉 Razor 未选用布局,现在我们暂时忽略,以后在详细介绍。对该页面添加内容。
调试后出现界面如下
4 添加动态输出
Web 应用程序平台的关键时构造并显示动态输出。在 MVC 中。控制器的工作时构造一些数据并传递给视图,而视图则负责把他渲染成 HTML。
将数据从控制器传递给视图的一种方式是使用 ViewBag (视图包)对象,他是 Controller 基类的一个成员。ViewBag 是一种动态对象,看可以给他赋任意属性,这些属性在随后渲染的视图中可用。下面演示了在 HomeController.cs 文件中传递一些简单的动态数据。
public ViewResult Index()
{
int Hour = DateTime.Now.Hour;
ViewBag.Greeting = Hour < 12 ? "Good Morning" : "Good afternoon";
return View();
}
当 ViewBag.Greeting 属性进行赋值时,便是为视图提供数据,Greeting 属性直到对其赋值的那一刻才会形成。为了获取到传递的数值,在 Index.cshtml 文件做相应修改。
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
@ViewBag.Greeting World(From the view)
</div>
</body>
</html>
注意:Greeting 可以是任意名称,你也可以写成 @ViewBag.name 只要和 Index 界面对应就可以实现值传递。
效果如下:
5 创建一个简单的数据录入程序
场景设置:假设朋友准备举办一场聚会,设计一个 Web 应用程序,对受邀人进行电子回复(RSVP);
- 一个显示晚会信息首页
- 一个用来回复的 (PVSP) 的表单
- 对 RVSP 表单验证,显示一个感谢画面
界面 Views/Home/Index.cshtml 文件添加内容:
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<link href="~/Content/Style.css" rel="stylesheet" />
<link href="~/Content/bootstrap.css" rel="stylesheet" />
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<div class="text-center">
@ViewBag.Greeting World(From the view)
<h2>
我们将会有一个愉悦的party
</h2>
<h3>您是否参加?</h3>
<div class="btn btn-success">
@Html.ActionLink("PVSP Now", "RvspForm")
</div>
</div>
</body>
</html>
设计一个数据模型:
添加模型类:
MVC 约定是将建立模型的类放在 “Models” 文件夹下,该文件夹是建立项目是自动创建的,右键 “解决方案” 窗口文件夹“Models”,从弹出窗选择“添加”--“类”,文件名设置为“GuestResponse.cs”,单击添加按钮,创建这个类编辑如下:
链接动作方法
在 Index.cshtml 添加一个指向 RSVP 表单的链接;
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<link href="~/Content/Style.css" rel="stylesheet" />
<link href="~/Content/bootstrap.css" rel="stylesheet" />
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<div class="text-center">
@ViewBag.Greeting World(From the view)
<h2>
我们将会有一个愉悦的party
</h2>
<h3>您是否参加?</h3>
<div class="btn btn-success">
@Html.ActionLink("PVSP Now", "RvspForm")
</div>
</div>
</body>
</html>
Html.ActionLink 是 HTMLde 辅助器方法 。MVC 框架附带一组内置的辅助器方法。可以方便地用来渲染 HTML 的链接,文本输入,复选框以及其他内容。ActionLink 一共两个参数,一个是显示文本,第二个是用户单击该连接产生的动作。此时单击该链接会报 404 错误,因为还没有 /Home/RsvpForm 该界面。此时,在 HomeController 类中添加一个 “RsvpForm” 的方法完成。
添加强类型视图
建立表单
编辑这个 RvspForm.cshtml 。
@model MVCStudy.Models.GuestResponse
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>RvspForm</title>
<link href="~/Content/bootstrap.css" rel="stylesheet" />
<link href="~/Content/bootstrap.css" rel="stylesheet" />
<link href="~/Content/bootstrap-reboot.css" rel="stylesheet" />
<link href="~/Content/bootstrap-reboot.min.css" rel="stylesheet" />
<style>
.btn a {color:white;text-decoration:none}
body{background-color:#F1F1F1;}
</style>
</head>
<body>
<div class="p">
</div>
@using (Html.BeginForm())
{
@Html.ValidationSummary()
<div class="form-group">
<label>Your Name :</label>
@Html.TextBoxFor(x => x.Name, new { @class = "formcontrol" })
</div>
<div class="form-group">
<label>Your Email :</label>
@Html.TextBoxFor(x => x.Email, new { @class = "formcontrol" })
</div>
<div class="form-group">
<label>Your phone : </label>
@Html.TextBoxFor(x => x.Phone, new { @class = "formcontrol" })
</div>
<div class="form-group">
<label>是否接受邀请?</label>
@Html.DropDownListFor(x => x.WillAttend, new[]{ new SelectListItem(){ Text="是,接受邀请",Value=bool.FalseString},new SelectListItem(){ Text = "否,不接受邀请", Value = bool.FalseString } },"请选择",new {@class="formcontrol"})
</div>
<div class="text-center"><input class="btn btn-success" type="submit" value="提交"></div>
}
</body>
</html>
设置启动 URL
注意: 保持特定页空白
处理表单
请求,来调用合适的方法。对 HomeController 类做修改。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCStudy.Models;
namespace MVCStudy.Controllers
{
public class HomeController : Controller
{
// GET: Home
public ViewResult Index()
{
int Hour = DateTime.Now.Hour;
ViewBag.Greeting = Hour < 12 ? "Good Morning" : "Good afternoon";
return View();
}
[HttpGet]
public ViewResult RvspForm()
{
return View();
}
[HttpPost]
public ViewResult RvspForm(GuestResponse guestResponse)
{
return View("Thanks",guestResponse);
}
}
}
using MVCStudy.Models 命名空间,这样可以直接使用 GuestResponse 模型类型,而不需要使用这个类的限定名。
使用模型绑定
渲染其他视图
View\Home\Thanks.cshtml。编辑此视图。
@model MVCStudy.Models.GuestResponse
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<link href="~/Content/bootstrap.css" rel="stylesheet" />
<title>Thanks</title>
<style>
body {
background-color: #F1F1F1;
}
</style>
</head>
<body>
@try
{
WebMail.SmtpServer = "smtp.example.com";
WebMail.SmtpPort = 587;
WebMail.EnableSsl = true;
WebMail.UserName = "mySmtpUsername";
WebMail.Password = "mySmtpPassword";
WebMail.From = "rsvps@example.com";
WebMail.Send("party-host@example.com", "RSVP Notifiaction", Model.Name + "is" + ((Model.WillAttend ?? false) ? "" : "not") + "attending");
}
catch(Exception)
{
@:<b>对不起,未能给您发送回复邮件</b>
}
<div class="text-center">
<h1>
Thank you,@Model.Name
</h1>
<div class="lead">
@if (Model.WillAttend == true)
{
@:感谢您的到来
}
else
{
@:您未能参加我们的Party,我们深感遗憾,感谢您的回复。
}
</div>
</div>
</body>
</html>
添加验证
注释属性进行定义。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace MVCStudy.Models
{
public class GuestResponse
{
[Required(ErrorMessage ="请确认您的姓名")]
public string Name { get; set; }
[Required(ErrorMessage = "请确认您的邮箱")]
[RegularExpression(".+\\@.+\\..+",ErrorMessage ="请输入有效邮箱")]
public string Email { get; set; }
[Required(ErrorMessage = "请确认您的电话")]
public string Phone { get; set; }
[Required(ErrorMessage = "请确认您是否接受邀请")]
public bool? WillAttend { get; set; }
}
}
ValidationSummary()(验证摘要)辅助器方法。
@model MVCStudy.Models.GuestResponse
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>RvspForm</title>
<link href="~/Content/bootstrap.css" rel="stylesheet" />
<link href="~/Content/bootstrap.css" rel="stylesheet" />
<link href="~/Content/bootstrap-reboot.css" rel="stylesheet" />
<link href="~/Content/bootstrap-reboot.min.css" rel="stylesheet" />
<style>
.btn a {color:white;text-decoration:none}
body{background-color:#F1F1F1;}
</style>
</head>
<body>
<div class="p">
</div>
@using (Html.BeginForm())
{
@Html.ValidationSummary()
<div class="form-group">
<label>Your Name :</label>
@Html.TextBoxFor(x => x.Name, new { @class = "formcontrol" })
</div>
<div class="form-group">
<label>Your Email :</label>
@Html.TextBoxFor(x => x.Email, new { @class = "formcontrol" })
</div>
<div class="form-group">
<label>Your phone : </label>
@Html.TextBoxFor(x => x.Phone, new { @class = "formcontrol" })
</div>
<div class="form-group">
<label>是否接受邀请?</label>
@Html.DropDownListFor(x => x.WillAttend, new[]{ new SelectListItem(){ Text="是,接受邀请",Value=bool.FalseString},new SelectListItem(){ Text = "否,不接受邀请", Value = bool.FalseString } },"请选择",new {@class="formcontrol"})
</div>
<div class="text-center"><input class="btn btn-success" type="submit" value="提交"></div>
}
</body>
</html>
高亮显示无效字段
的内容:
.field-validation-error {
color: #f00;
}
.field-validation-valid{display:none;}
.input-validation-error{border:1px solid #f00;background-color:#fee;}
.validation-summary-errors{font-weight:bold;color:#f00}
.validation-summary-valid{display:none}
在 RvsvpForm.cshtml 中添加 Link 元素。
直接从解决方案中用鼠标拖拽文件到相应位置就能自动写 Link.
设置内容样式
使用 NuGet 安装 Bootstrap;
找到 Bootstrap 安装即可。
设置 Index 视图
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<link href="~/Content/Style.css" rel="stylesheet" />
<link href="~/Content/bootstrap.css" rel="stylesheet" />
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<div class="text-center">
@ViewBag.Greeting World(From the view)
<h2>
我们将会有一个愉悦的party
</h2>
<h3>您是否参加?</h3>
<div class="btn btn-success">
@Html.ActionLink("PVSP Now", "RvspForm")
</div>
</div>
</body>
</html>
设置 RsvpForm 视图
@model MVCStudy.Models.GuestResponse
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>RvspForm</title>
<link href="~/Content/Style.css" rel="stylesheet" />
<link href="~/Content/bootstrap.css" rel="stylesheet" />
<style>
.btn a {color:white;text-decoration:none}
body{background-color:#F1F1F1;}
</style>
</head>
<body>
<div class="text-center">
@using (Html.BeginForm())
{
@Html.ValidationSummary()
<div class="form-group">
<label>Your Name :</label>
@Html.TextBoxFor(x => x.Name, new { @class = "formcontrol" })
</div>
<div class="form-group">
<label>Your Email :</label>
@Html.TextBoxFor(x => x.Email, new { @class = "formcontrol" })
</div>
<div class="form-group">
<label>Your phone : </label>
@Html.TextBoxFor(x => x.Phone, new { @class = "formcontrol" })
</div>
<div class="form-group">
<label>是否接受邀请?</label>
@Html.DropDownListFor(x => x.WillAttend, new[] { new SelectListItem() { Text = "是,接受邀请", Value = bool.FalseString }, new SelectListItem() { Text = "否,不接受邀请", Value = bool.FalseString } }, "请选择", new { @class = "formcontrol" })
</div>
<div class="text-center"><input class="btn btn-success" type="submit" value="提交"></div>
}
</div>
</body>
</html>
设置 Thanks 视图样式
@model MVCStudy.Models.GuestResponse
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<link href="~/Content/bootstrap.css" rel="stylesheet" />
<title>Thanks</title>
<style>
body {
background-color: #F1F1F1;
}
</style>
</head>
<body>
@try
{
WebMail.SmtpServer = "smtp.example.com";
WebMail.SmtpPort = 587;
WebMail.EnableSsl = true;
WebMail.UserName = "mySmtpUsername";
WebMail.Password = "mySmtpPassword";
WebMail.From = "rsvps@example.com";
WebMail.Send("party-host@example.com", "RSVP Notifiaction", Model.Name + "is" + ((Model.WillAttend ?? false) ? "" : "not") + "attending");
}
catch(Exception)
{
@:<b>对不起,未能给您发送回复邮件</b>
}
<div class="text-center">
<h1>
Thank you,@Model.Name
</h1>
<div class="lead">
@if (Model.WillAttend == true)
{
@:感谢您的到来
}
else
{
@:您未能参加我们的Party,我们深感遗憾,感谢您的回复。
}
</div>
</div>
</body>
</html>
源码下载:https://download.csdn.net/download/qq_21419015/10433092
全文完
本文由 简悦 SimpRead 优化,用以提升阅读体验
使用了 全新的简悦词法分析引擎 beta,点击查看详细说明
1 创建 MVC 项目2 添加第一个控制器3 渲染 Web 界面4 添加动态输出5 创建一个简单的数据录入程序添加模型类:链接动作方法添加强类型视图建立表单添加验证高亮显示无效字段设置内容样式