1.MVC驗證,MVC3自帶的驗證有
.NET 框架中的System.ComponentModel.DataAnnotations命名空間包括了衆多可爲你所用的內置驗證特性,介紹用的最多的其中的四個:
[Required], [StringLength], [Range], 和 [RegularExpression]。
定義自己的定製驗證特性,然後應用它們。你可以通過繼承自
System.ComponentModel.DataAnnotations命名空間中 的ValidationAttribute基類,定義完全定製的特性。
服務器端校驗只需要在Action中校驗:ModelState.IsValid屬性即可。true就是校驗通過,false反之不通過。
要使用客戶端驗證,必須引入JS腳本支持(jq的校驗)
添加語句
<% Html.EnableClientValidation(); %> (MVC3 、4 中默認開啓)
@{ Html.EnableClientValidation(false); }WebConfig,全局配置ClientValidationEnabled,設置爲true
<add key="ClientValidationEnabled" value="true" />2.MVC自帶的ajax,先引用jquery和視圖ajax,參數參考具體文檔
@using (Ajax.BeginForm("GetData", "Ajax", new AjaxOptions() { Confirm = "你是否要提交嗎", HttpMethod = "POST", InsertionMode = InsertionMode.Replace, UpdateTargetId = "id1", OnSuccess = "successFunction", LoadingElementId = "loading" })) { <div> 用戶名<input type="text" name="username" /> 密碼<input type="password" name="pwd" /> <input type="submit" value="提交" /> </div> <div id="id1"></div> <div id="loading"></div> }3.過濾器
微軟提供的默認的4種過濾器
Authorizazation
Action filter
Result filter
Exception filter
在驗證和動作、視圖、異常,當出現某種情況時,就執行該段代碼
public class MyActionFilterAttribute : ActionFilterAttribute { public string Name { get; set; } public override void OnActionExecuted(ActionExecutedContext filterContext) { base.OnActionExecuted(filterContext); HttpContext.Current.Response.Write("<br/>" + Name); } } 可以用過濾器做Session驗證,要執行過濾器,只要在控制器或Action上打上標籤,對應的Action請求時就 先執行過濾器,如果打在控制器上,裏面所有的action都不需要在標誌
[MyActionFilter(Name="home index")] public ActionResult Index() { ViewData["key"] = DateTime.Now; return View(); }如果讓所有的都要執行,只需在
FilterConfig.cs中註冊一個就行,優先級最低
public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); filters.Add(new MyActionFilterAttribute() { Name = "global" }); }在控制器上加上
[AttributeUsage(AttributeTargets.All,AllowMultiple=true)]可以使一個Action執行多個過濾器
4.異常過濾器
public class MyExceptionAttribute : HandleErrorAttribute { public override void OnException(ExceptionContext filterContext) { base.OnException(filterContext); //當出現錯誤的時候 //1.記錄日記 //2.頁面跳轉到錯誤或者 //3.多個線程同時訪問一個日誌,考慮使用內存隊列,爲了考慮性能,引入分佈式隊列Redis //4.加入觀察者模式,可以寫到不同地方,應對不同變化,引入設計模式,寫入不同變化點 //5.log4net HttpContext.Current.Response.Redirect("/home/index"); } } 在Filter.cs中配置自己的過濾器
filters.Add(new MyExceptionAttribute());
5.MVC區域功能
Asp.Net MVC提供了區域的功能,可以很方便的爲大型的網站劃分區域。
可以讓我們的項目不至於太複雜而導致管理混亂,有了區域後,每個模塊的頁面都放入相應的區域內進行管理很方便。
在項目上右擊創建新的區域
區域的功能類似一個小的MVC項目,麻雀雖小五臟俱全,有自己的控制器、模型、視圖、路由設置
區域的路由設置是最優先的
6.局部視圖和局部渲染
@{Html.RenderPartial("MVCAjax"); Html.RenderAction(""); } 頁面上做一個嵌套使用html就用frameset和iframe,下載可以用Html.RenderPartial,在webform內使用用 戶控件7.MVC模板頁