ASP.NET MVC控制器裡捕獲視圖的錯誤驗證資訊(ErrorMessage)

來源:互聯網
上載者:User

標籤:style   blog   http   ar   io   color   os   sp   for   

 

ViewModel類:

    /// <summary>    /// 評論用驗證視圖    /// </summary>    public partial class VCreateShopComment    {        [Required(AllowEmptyStrings = false, ErrorMessage = "WangWang是必須的")]        public string WW { get; set; }        [Required(AllowEmptyStrings = false, ErrorMessage = "必須評論")]        [StringLength(200, ErrorMessage = "評論內容不能超過{0}字")]        public string CommentText { get; set; }        [Range(1, 5, ErrorMessage = "評分要在{1}到{2}之間")]        public short Score { get; set; }        //[Range(0, int.MaxValue, ErrorMessage = "您的賬戶無效")]        public int ID{ get; set; }    }

 

控制器

[HttpPost]public ActionResult Add(VCreateShopComment v)        {   if (ModelState.IsValid)            {              //做愛做的事            }            StringBuilder sb = new StringBuilder();            var errors = ModelState.Values;            foreach (var item in errors)            {                foreach (var item2 in item.Errors)                {
          if (!item2.ErrorMessage.IsNullOrWhiteSpace())                   {                       sb.AppendLine(item2.ErrorMessage + "<br />");                   }
} } return Content(sb.ToString()); }

 

錯誤的輸出用2次遍曆就行了,前提是,對於每個驗證特性ErrorMessage 是要有的

 

ASP.NET MVC控制器裡捕獲視圖的錯誤驗證資訊(ErrorMessage)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.