ASP.NET?MVC遍歷驗(yàn)證ModelState的錯誤信息
在ASP.NET MVC中,ModelState中包含了驗(yàn)證失敗的錯誤信息,具體被存儲在ModelState.Values[i].Errors[j].ErrorMessage屬性中。當(dāng)然,通過打斷點(diǎn),單步調(diào)試可以查看具體的驗(yàn)證失敗錯誤信息,但有時候希望把ModelState中的驗(yàn)證失敗信息遍歷顯示出來。
ModelState類型是ModelStateDictionary,ModelStateDictionary是一個字典集合,鍵是模型的各個屬性,值是模型各個屬性對應(yīng)的ModelState。
ModelState的Errors屬性存儲了所有驗(yàn)證失敗信息,是一個ModelErrorCollection類型,ModelErrorCollection是一個ModelError的集合,而ModelError的ErrorMessage屬性包含了驗(yàn)證失敗錯誤信息。
大致是這樣:
- ModelStateDictionary實(shí)際上是IDictionary<string, ModelState>類型
- ModelState.Errors屬性實(shí)際上是ModelErrorCollection類型
- ModelErrorCollection實(shí)際上是ICollection<ModelError>類型
- ModelError.ErrorMessage屬性存儲著所有驗(yàn)證失敗信息
如何把驗(yàn)證失敗信息顯示出來呢?
{"屬性1","屬性1驗(yàn)證失敗錯誤信息1"},
{"屬性1","屬性1驗(yàn)證失敗錯誤信息2"},
{"屬性2","屬性2驗(yàn)證失敗錯誤信息1"}
......
想寫成如上的樣子,通過json讀取出來,在后臺遍歷,都可以。
那就先抽象出一個顯示錯誤信息的模型。
public class ShowError { public ShowError(string key, string message) { Key = key; Message = message; } public string Key { get; set; } public string Message { get; set; } }
由于ModelState是ModelStateDictionary類型,那就針對ModelStateDictionary類型寫一個擴(kuò)展方法。就是把ModelStateDictionary中的驗(yàn)證失敗信息連同對應(yīng)的屬性讀取出來,注入到ShowError這個模型中,并最終得到一個IEnumerable<ShowError>集合。
public static class ModelStateExtensions { public static IEnumerable<ShowError> AllModelStateErrors(this ModelStateDictionary modelState) { var result = new List<ShowError>(); //找到出錯的字段以及出錯信息 var errorFieldsAndMsgs = modelState.Where(m => m.Value.Errors.Any()) .Select(x => new {x.Key, x.Value.Errors}); foreach (var item in errorFieldsAndMsgs) { //獲取鍵 var fieldKey = item.Key; //獲取鍵對應(yīng)的錯誤信息 var fieldErrors = item.Errors .Select(e => new ShowError(fieldKey, e.ErrorMessage)); result.AddRange(fieldErrors); } return result; } }
再來一個最終用來測試驗(yàn)證失敗錯誤信息的視圖模型。
public class Student { public int Id { get; set; } [Required(ErrorMessage = "必填")] [StringLength(5, ErrorMessage = "長度1-5位")] public string Name { get; set; } [Required(ErrorMessage = "必填")] public int Age { get; set; } [Required(ErrorMessage = "必填")] [Range(typeof(Decimal), "0", "100", ErrorMessage = "{0} 必須是數(shù)字介于 {1} 和 {2}之間.")] public decimal Score { get; set; } }
在HomeController中,有一個Action用來呈現(xiàn)Student的強(qiáng)類型視圖頁,有一個Action用來把從ModelState中獲取到的所有屬性以及對應(yīng)的驗(yàn)證失敗信息以json格式返回給前臺視圖。
public class HomeController : Controller { public ActionResult Index() { return View(new Student()); } [HttpPost] public ActionResult GetErrors(Student student) { if (ModelState.IsValid) { return Content("沒有錯誤信息~~"); } Response.StatusCode = 400; Response.TrySkipIisCustomErrors = true; var modelErrors = ModelState.AllModelStateErrors(); return Json(modelErrors); } }
在Home/Index.cshtml視圖中,當(dāng)點(diǎn)擊"提交"按鈕,在控制臺顯示驗(yàn)證失敗信息。
@model MvcApplication1.Models.Student @{ ViewBag.Title = "Index"; Layout = "~/Views/Shared/_Layout.cshtml"; } <h2>Index</h2> @using (Html.BeginForm("GetErrors", "Home", FormMethod.Post, new {id = "addForm"})) { @Html.TextBoxFor(m => m.Name) <br /> @Html.TextBoxFor(m => m.Age) <br /> @Html.TextBoxFor(m => m.Score) <br /> <input type="button" id="up" value="提交" /> } @section scripts { <script type="text/javascript"> $(function () { $('#up').on('click', function () { $.post('@Url.Action("GetErrors")', $('#addForm').serialize()).fail(function(error) { var response = JSON.parse(error.responseText); for (var i = 0; i < response.length; i++) { var e = response[i]; var fieldKey = e.Key; var message = e.Message; console.log(fieldKey + ': ' + message); } }); }); }); </script> }
最終,在控制臺顯示驗(yàn)證失敗信息如下:
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,謝謝大家對腳本之家的支持。如果你想了解更多相關(guān)內(nèi)容請查看下面相關(guān)鏈接
相關(guān)文章
Asp.net 中使用GridView控件實(shí)現(xiàn)Checkbox單選
在GridView控件中,第0列有放一個CheckBox控件,現(xiàn)想實(shí)現(xiàn)對CheckBox進(jìn)行單選,怎么實(shí)現(xiàn)呢?下面小編通過本文給大家分享Asp.net 中使用GridView控件實(shí)現(xiàn)Checkbox單選功能,一起看看吧2017-07-07ASP.NET Cookie 操作實(shí)現(xiàn)
本節(jié)中的主題描述如何在 ASP.NET Web 應(yīng)用程序中創(chuàng)建 Cookie。Cookie 是一些小的文本文件,服務(wù)器和瀏覽器在收到每個頁請求時交換它們,您還可以使用這些小文本文件來存儲幫助針對每個用戶自定義您的應(yīng)用程序的信息。2009-11-11"PageMethods未定義"或"對象不支持此屬性或方法"解決方法分享
PageMethods未定義或?qū)ο蟛恢С执藢傩曰蚍椒ń鉀Q方法,需要的朋友可以參考下。2010-12-12ASP.NET Core MVC學(xué)習(xí)之視圖組件(View Component)
這篇文章主要給大家介紹了關(guān)于ASP.NET Core MVC學(xué)習(xí)之視圖組件(View Component)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用ASP.NET Core MVC具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08- 就是有時候窗口不能夠成功置頂,這時需要重新切換下標(biāo)簽,就可以置頂了,本文介紹C# SetWindowPos實(shí)現(xiàn)窗口置頂?shù)姆椒?/div> 2012-12-12
HttpRequest Get和Post調(diào)用其他頁面的方法
HttpRequest Get和Post調(diào)用其他頁面的方法,需要的朋友可以參考一下2013-03-03最新評論