• 模型(Model) 「數據模型」(Model)用於封裝與應用程序的業務邏輯相關的數據以及對數據的處理方法。「模型」有對數據直接訪問的權力,例如對數據庫的訪問。「模型」不依賴「視圖」和「控制器」,也就是說,模型不關心它會被如何顯示或是如何被操做。可是模型中數據的變化通常會經過一種刷新機制被公佈。爲了實現這種機制,那些用於監視此模型的視圖必須事先在此模型上註冊,從而,視圖能夠了解在數據模型上發生的改變。javascript
• 視圖(View) 視圖層可以實現數據有目的的顯示(理論上,這不是必需的)。在視圖中通常沒有程序上的邏輯。爲了實現視圖上的刷新功能,視圖須要訪問它監視的數據模型(Model),所以應該事先在被它監視的數據那裏註冊。html
• 控制器(Controller) 控制器起到不一樣層面間的組織做用,用於控制應用程序的流程。它處理事件並做出響應。「事件」包括用戶的行爲和數據模型上的改變。java
• 1. 當第一個請求從客戶端發起的時候,首先執行的是Global.asax中的Application_Start()方法來完成一些初始化工做,其中重要的一步是RegisterRoutes方法,這個方法指定了如何將url映射到具體的方法上,稍後詳解。jquery
• 2. 根據第一步中指定的映射表生成一個RouteData對象,利用這個對象來建立一個RequestContext對象。web
• 3. MvcRouteHandler建立一個MvcHandler,並將RequestContext對象傳給MvcHandler。ajax
• 4. MvcHandler對象利用RequestContext對象肯定一個IControllerFactory對象來建立Controller對象。數據庫
• 5. MvcHandler對象調用Controller對象的Execute()方法。express
• 6. Controller的ControolerActionInvoker對象決定調用controller的哪一個具體的action方法。緩存
• 7. Action方法接受用戶參數,執行方法,返回一個Result類型的對象。安全
使用@model關鍵字能夠定義一個Action裏所對應的一個模型(常常能夠叫他實體類),
實際上是對動態變量進行實例化,這樣就能夠直接在cshtml文件中調用「Model」變量。
而這個模型的實例,須要經過Controller進行傳輸,若是沒有則「Model」將爲null。
模型能夠是一個實體類,也能夠是一個列表實例,字典對象均可以進行定義,可是和
Controller中的Action傳回來的實例必定要同樣,不然將會出現錯誤。例如咱們獲取
用戶實例,而且在頁面上呈現用戶的具體信息,這樣就能夠將用戶實例返回給前臺
Model類中能夠添加的驗證標記:
1. 必填字段
[Required]
public string FirstName { get; set; }
2. 字段長度
至多n位:
[StringLength(160)]
public string FirstName { get; set; }
要求至少n位:
[StringLength(160, MinimumLength=3)]
public string FirstName { get; set; }
3. 正則驗證
[RegularExpression(@」[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}」)]
public string Email { get; set; }
4. 範圍
[Range(35,44)]
public int Age { get; set; }
小數的狀況:
[Range(typeof(decimal), 「0.00」, 「49.99」)]
public decimal Price { get; set; }
5. 服務端參與的驗證
[Remote(「CheckUserName」, 「Account」)]
public string UserName { get; set; }
而後在AccountController裏指定一個CheckUserName方法:
public JsonResult CheckUserName(stringusername)
{
var result = Membership.FindUsersByName(username).Count == 0;
return Json(result, JsonRequestBehavior.AllowGet);
}
6. 比較
[RegularExpression(@」[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}」)]
public string Email { get; set; }
[Compare(「Email」)]
public string EmailConfirm { get; set; }
7. 自定義錯誤消息
正則:
[RegularExpression(@」[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}」,
ErrorMessage=」Email doesn’tlook like a valid email address.」)]
public string Email { get; set; }
普通文本:
[Required(ErrorMessage=」Your last name isrequired」)]
[StringLength(160, ErrorMessage=」Your lastname is too long」)]
public string LastName { get; set; }
佔位符:
[Required(ErrorMessage=」Your {0} isrequired.」)]
[StringLength(160, ErrorMessage=」{0} is toolong.」)]
public string LastName { get; set; }
Shared/_Layout.cshtml
ActionLink
@Html.ActionLink("Text", "Index", "Home", new { page = 1 }, new { id = "link1" })
解釋爲:
<a href="/?page=1" id="link1">Text</a>
RouteLink
其實就是用一個新創建的RouteValueDictionary的對象(new{}所實例化的對象將會等價轉換爲RouteValueDictionary)來替原來的Action,Controller字符串的單獨指定。
示例:@Html.RouteLink("Text",new { action = "index", page = 1 }, new { id="link1"})
可經過路由名稱指定指向某路由路徑。
示例:@Html.RouteLink("關於","about", new { page = 1 }, new { id = "link1" })
其中about爲路由名稱
表單
表單兩種方式:
一、<form action="@Url.Action("Index","Home")"method="post"></form>
二、@using(Html.BeginForm("Index","Movies",FormMethod.Get)){}
三、綁定下拉框示例:
@Html.DropDownList("movieGenre","All")
<a href='<%=Url.Action("DemoAction","DemoController", new{id=2,category=5 },"https")%>' title="">指定傳輸協議生成URL</a><br/>
解釋爲:<ahref='https://localhost/DemoController/DemoAction?id=2&category=5'title="">指定傳輸協議生成URL</a><br />
從Model獲取數據,而後經過ViewData傳遞給View數據
可使用不一樣的View呈現數據
ActionResult的其它返回值:JsonResult、RedirectResult
PartialView(自定義控件)、View方法
ViewData、TempData傳值
ViewData只能在當前Action中有效
TempData能夠相似於Session同樣到其它頁面仍然存在,但只限一頁的訪問
TempData通常用於臨時的緩存內容或拋出錯誤頁面時傳遞錯誤信息
ValidateAntiForgeryToken 特性,這個特性用來阻止僞造的請求,它和視圖(Views\Movies\Edit.cshtml)中的@Html.AntiForgeryToken() 是成對出現的。
顯示驗證錯誤信息
@Html.ValidationSummary(true, "",new { @class = "text-danger" })
一、顯示當前頁面層
二、提交數據到controller中方法以下圖代碼
三、ajaxHelper
一、Ajax異步請求ContentController
ContentController直接以字符串形式返回實例的內容,在Index.cshtml中使用ActionLink,以下:
@Ajax.ActionLink("AjaxContentController","getEntry", new { id = item.Id }, new AjaxOptions { HttpMethod ="Post", UpdateTargetId = "detailsID", InsertionMode =InsertionMode.Replace })
相應的Controller:
public string getEntry(int id = 0) {
GuestbookEntryentry = _db.Entries.First(c => c.Id == id);
returnentry.Details;
}
二、使用Json格式返回
@Ajax.ActionLink("AjaxJsonController","JsonDetails", new { id = item.Id }, new AjaxOptions { HttpMethod ="Post", InsertionMode = InsertionMode.Replace, OnSuccess = "Show();"})
相應的Controller:
public ActionResult JsonDetails(int id = 0)
{
GuestbookEntryentry = _db.Entries.First(c => c.Id == id);
return Json(entry,JsonRequestBehavior.AllowGet);
}
注意:在使用Json格式返回數據時,因爲安全緣由,只接收Post請求,所以在這裏使用JsonRequestBehavior.AllowGet來容許Get方式請求。
同時須要在Index.cshtml中添加請求成功的相應函數Show:
<script type="text/javascript">
function Show(data) {
$("#detailsID").html("姓名:" + data.Name+ " 消息:" + data.Message);
}
</script>
一、多個區域中增長多個member,而每一個member中存在一個路由
二、在項目中能夠設置一個總路由指定到某個命名空間。而後在每一個member區域設置單獨路由。
MapRoute是RouteCollection的擴展方法,同時還有IngnoreRoute,而Add則是實例方法,相對來講要使用Add來調用比較複雜(包含剛纔提到的5大屬性),而MapRoute則相對簡潔。
Add
routes.Add(new Route("blog/{action}/{author}",
new RouteValueDictionary { {"action", "show" }, {"author", "miracle"} },
new MvcRouteHandler()));
MapRoute
routes.MapRoute(
"Article", // 路由名稱
"blog/{action}/{author}", // 帶有參數的 URL
new { controller = "Home", action = "show", author = "miracle" }
);
當用戶輸入URL地址發送請求時,UrlRoutingModule類就會到路由表(RouteTable)中解析與請求匹配的路由,而後將該路由分發到路由處理程序(IRouteHandler),並連同RequestContext一塊兒再次分發到Mvc處理程序(IHttpHandler),定位相關的控制器並執行相關的動做實現輸出。如下的整個過程的示意圖。
在傳統的Web站點中使用路由(通常狀況下用戶將傳統站點轉化爲MVC站點的項目遷移過渡)。主要包含如下兩個步驟:
一、常見實現IRouteHandler接口的WebFormRouteHandler類,返回實現IHttpHandler接口的實例化對象(實際上任何一個Page都是一個IHttpHandler實例對象)。
public class WebFormRouteHandler : IRouteHandler
{
public stringVirtualPath { get; private set; }
//初始化虛擬路徑
publicWebFormRouteHandler(string virtualPath)
{
this.VirtualPath= virtualPath;
}
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
//建立實例化的頁面對象
var page =BuildManager.CreateInstanceFromVirtualPath(VirtualPath, typeof(Page)) as IHttpHandler;
return page;
}
}
二、配置全局應用程序類(Global.asax),實現路由的映射。
routes.MapMvcAttributeRoutes(); //Attribute路由註冊
AreaRegistration.RegisterAllAreas();//區域路由註冊
注:增長區域以後,防止路由重複,需在默認路由中爲命名空間賦值。
[Route("Home/Index/{id}")]
public ActionResult Index() {... }
與通用路由是否能夠一塊兒使用待驗證,已經驗證,能夠一塊兒使用。以Attribute這裏爲主。
[Route("Home/Index/{id?}")]
匹配//Home/Index或者/Home/Index/id
//匹配:/books/lang
//匹配:/books/lang/en
//匹配:/books/lang/he
//若是URL不傳遞 lang 參數,則lang的值爲「en」
[Route("books/lang/{lang=en}")]
//匹配:/Home
[Route("Home")]
publicActionResult Index() { ... }
//匹配:/ Home/5
[Route("Home/{id}")]
publicActionResult Show(int id) { ... }
//匹配:/ Home/5/edit
[Route("Home/{id}/edit")]
publicActionResult Edit(int id) { ... }
或者在controller前面增長屬性[RoutePrefix("Home")]
[RoutePrefix("promotions")]
[Route("{action=index}")]
默認promotions,action爲index
ActionResult前面增長[Route]則覆蓋默認路由。
路由約束可讓你指定參數的類型以及範圍等,格式爲:{參數:約束},舉例以下:
// 匹配: /users/5
[Route("users/{id:int}"]
// 這裏約束了參數「id」必須爲整數類型
publicActionResult GetUserById(int id) { ... }
下面是支持的路由約束列表:
Constraint |
Description |
Example |
alpha |
Matches uppercase or lowercase Latin alphabet characters (a-z, A-Z) |
{x:alpha} |
bool |
Matches a Boolean value. |
{x:bool} |
datetime |
Matches a DateTime value. |
{x:datetime} |
decimal |
Matches a decimal value. |
{x:decimal} |
double |
Matches a 64-bit floating-point value. |
{x:double} |
float |
Matches a 32-bit floating-point value. |
{x:float} |
guid |
Matches a GUID value. |
{x:guid} |
int |
Matches a 32-bit integer value. |
{x:int} |
length |
Matches a string with the specified length or within a specified range of lengths. |
{x:length(6)} {x:length(1,20)} |
long |
Matches a 64-bit integer value. |
{x:long} |
max |
Matches an integer with a maximum value. |
{x:max(10)} |
maxlength |
Matches a string with a maximum length. |
{x:maxlength(10)} |
min |
Matches an integer with a minimum value. |
{x:min(10)} |
minlength |
Matches a string with a minimum length. |
{x:minlength(10)} |
range |
Matches an integer within a range of values. |
{x:range(10,50)} |
regex |
Matches a regular expression. |
{x:regex(^\d{3}-\d{3}-\d{4}$)} |
你能夠在一個參數後面應用多個約束,用冒號分隔它們,以下:
// 匹配: /users/5
// 可是不匹配 /users/10000000000 由於id的值已經超過了int.MaxValue,
// 也不匹配 /users/0 由於後面有個min(1)約束,id 的值必須大於等於 1.
[Route("users/{id:int:min(1)}")]
publicActionResult GetUserById(int id) { ... }
看上例
[Route("menu",Name = "mainmenu")]
publicActionResult MainMenu() { ... }
可使用Url.RouteUrl 來生成相應的 URL:
<ahref="@Url.RouteUrl("mainmenu")">Main menu</a>
Area概念對組織大型Web應用程序頗有幫助,在Attribute路由中固然少不了對它的支持,只要使用 [RouteArea],就能夠把 Controller 歸屬到某一個 Area 下
刪除Area 下的AreaRegistration 類
[RouteArea("Admin")]
[RoutePrefix("menu")]
[Route("{action}")]
publicclass MenuController : Controller
{
//匹配:/admin/menu/login
publicActionResult Login() { ... }
}
新建文件夾:Extensions,文件夾Extensions中添加自定義擴展。
使用時,view頁面必須加入:@using MVCMovie.Extensions;//自定義。
頁面引用如:@Html.QINLabel("male", "男")
示例:
public static string Label(this HtmlHelperhelper, string name, string value)
{
return string.Format("<labelfor='{0}'>{1}</label><br />", name, value);
}
新增擴展類
控制器
public class AjaxHelperExtController :Controller
{
//
// GET: /AjaxHelperExt/
public ActionResult AjaxHelperExt()
{
return View();
}
public ActionResult GetTime()
{
return Content("Now Time:" + DateTime.Now.ToString());
}
}
最後在jquery.unobtrusive-ajax.js裏面加上TextBox的Keyup事件綁定
$("input[type=text][data-ajax=true]").live("keyup",function (evt) {
asyncRequest(this, { type: "GET" ,data: [{ name:$(this).attr('name'), value: $(this).val()}] });
});
調用
<divid="divTime"></div>
@Ajax.Textbox("search",
new AjaxOptions
{
Url = @Url.Action("GetTime") ,
UpdateTargetId = "divTime",
InsertionMode = InsertionMode.Replace
},
new { size = 50 })
注:同時須要在頁面中引入MicrosoftAjax.js,MicrosoftMvcAjax.js
在web.config中增長client side validation and unobtrusive javascript 兩個配置
<addkey="ClientValidationEnabled" value="true" />
<addkey="UnobtrusiveJavaScriptEnabled" value="true" />
原文來自 http://www.cnblogs.com/gxlinhai/p/4261471.html