https://blog.csdn.net/qq_21419015/article/details/80420815

第一个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 添加显示内容

渲染:视图引擎解释视图文件,转化为html文件;

传递:将渲染后的html标记传给客户端;

呈现:浏览器将html标识显示为web页面。

将数据从控制器传递给视图的一种方法是使用 ViewBag (视图包)对象,ViewBag 是Controller基类的一个成员。

public ViewResult Index()

{
  int Hour = DateTime.Now.Hour;
  ViewBag.Greeting = Hour < 12 ? "Good Morning" : "Good afternoon";
  return View();
}

Greeting属性直到对其赋值的那一刻才会形成。

@{
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 是HTML辅助器方法 。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视图

<html>
<head></head>
<body>
@{ Layout = null; }
<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" />
<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视图

<html>
<head></head>
<body>
@model MVCStudy.Models.GuestResponse @{ Layout = null; }
<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>
<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视图样式

<html>
<head></head>
<body>
@model MVCStudy.Models.GuestResponse @{ Layout = null; }
<meta name="viewport" content="width=device-width" />
<link href="~/Content/bootstrap.css" rel="stylesheet" />
<title>Thanks</title>
<style>
body {
background-color: #F1F1F1;
}
</style> @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

ASP.NET + MVC5 入门完整教程三 (上) ---第一个MVC项目的更多相关文章

  1. ASP.NET + MVC5 入门完整教程三 (下) ---MVC 松耦合

    建立松耦合组件 MVC 模式最重要的特性之一视他支持关注分离,希望应用程序中的组件尽可能独立,只有很少的几个可控依赖项.在理想的情况下,每个组件都不了解其他组件,而只是通过抽象接口来处理应用程序的其他 ...

  2. ASP.NET + MVC5 入门完整教程七 -—-- MVC基本工具(上)

    https://blog.csdn.net/qq_21419015/article/details/80474956 这里主要介绍三类工具之一的 依赖项注入(DI)容器,其他两类 单元测试框架和模仿工 ...

  3. ASP.NET + MVC5 入门完整教程八 -—-- 一个完整的应用程序(上)

    https://blog.csdn.net/qq_21419015/article/details/80509513 SportsStore 1.开始创建Visual Studio 解决方案和项目这里 ...

  4. ASP.NET + MVC5 入门完整教程四---MVC 中使用扩展方法

    https://blog.csdn.net/qq_21419015/article/details/80433640 1.示例项目准备1)项目创建新建一个项目,命名为LanguageFeatures ...

  5. ASP.NET + MVC5 入门完整教程二

    原文链接:https://blog.csdn.net/qq_21419015/article/details/80318046 从前端UI开始 MVC分离的比较好,开发顺序没有特别要求,先开发哪一部分 ...

  6. ASP.NET + MVC5 入门完整教程八 -—-- 一个完整的应用程序(下)

    https://blog.csdn.net/qq_21419015/article/details/80802931 SportsStore 1.导航 添加导航控件 如果客户能够通过产品列表进行分类导 ...

  7. ASP.NET + MVC5 入门完整教程五 --- Razor (模型与布局)

    https://blog.csdn.net/qq_21419015/article/details/80451895 1.准备示例项目 为了演示Razor,使用VS创建一个名称为“Razor”的新项目 ...

  8. ASP.NET + MVC5 入门完整教程七 -—-- MVC基本工具(下)

    https://blog.csdn.net/qq_21419015/article/details/80493633 Visual Stdio 的单元测试

  9. asp.net + MVC5 入门完整教程一

    原文链接:https://blog.csdn.net/qq_21419015/article/details/80311918原创凌霜残雪 最后发布于2018-05-14 17:26:30 阅读数 3 ...

随机推荐

  1. 【spring boot】SpringBoot初学(1) - Hello World

    前言 此文只是记录自己简单学习spring boot的笔记.所以,文章很多只是初步理解,可能存在严重错误. 一.Spring boot的初步理解 1.spring boot的目标 (摘自:spring ...

  2. java中equals与==号的区别

    1.==号对于基本数据类型来说,比较的是值,对于引用数据类型来说比较的是地址值 2.equals方法在object类中,比较的是地址值,但是String类重写了Object类中的equals方法,所以 ...

  3. CentOS 7 部署 Redis(单机版)

    一.部署环境说明 软件 版本 安装包 CentOS 7.2 CentOS 7.2 Redis 4.0.14 redis-4.0.14.tar.gz 二.开始部署 安装gcc依赖 [root@bmsof ...

  4. 咸鱼的ACM之路:动态规划(DP)学习记录

    按挑战程序设计竞赛介绍的顺序记录一遍学习DP的过程. 1. 01背包问题 问题如下: 有N个物品,每个物品(N[i])都有一定的体积(W[i]),和一定的价值(V[i]) 现在给定一个背包,背包的容量 ...

  5. win10中安装jdk1.8

    一.JDK下载 两种方法,第一种是从官网下载:第二种是拿来主义,小拿直接给你网盘地址.不过,作为java新手,最好还是学会去官网下载. 官网下载的文件才是最安全的,从不靠谱第三方下载有可能安装包有缺失 ...

  6. Leetcode 995. K 连续位的最小翻转次数

    题目: 在仅包含 0 和 1 的数组 A 中,一次 K 位翻转包括选择一个长度为 K 的(连续)子数组,同时将子数组中的每个 0 更改为 1,而每个 1 更改为 0. 返回所需的 K 位翻转的次数,以 ...

  7. Conference deadlines

    1. NLP/IR/DM/ML Conference Deadlines(Updating) Two Principles of Deadlines:1. All deadlines converge ...

  8. Selenium3+python自动化016-Selenium Grid

    一.Selenium Grid介绍 1.概念 Selenium Grid组件专门用于远程分布式测试或并发测试,通过并发执行测试用例的方式可以提高测试用例的执行速度和效率,解决界面自动化测试执行速度过慢 ...

  9. Codeforces 1303E. Erase Subsequences 代码(dp 字符串压缩一维状态优化)

    https://codeforces.com/contest/1303/problem/E #include<bits/stdc++.h> using namespace std; ; i ...

  10. 134.cookie、session的工作机制

    cookie和session (1)cookie:在网站中,http请求时无状态的,也就是说即使第一次和服务器连接后并且登录成功后,第二次请求服务器依然不能知道当前请求的是哪个用户(在中国我们因为IP ...