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>

設計一個數據模型:

添加模型類:

鏈接動作方法
在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
