ASP.NET MVC3 ModelState.IsValid為false的問題

來源:互聯網
上載者:User

標籤:使用   strong   os   問題   io   cti   

模型驗證通常在submit後調用Action之前進行驗證,eg:

 

 public class ZhengXing
    {
        [Key]
        public int ZhengXingId { get; set; }                   //使用Key關鍵字要引用System.ComponentModel.DataAnnotations


        [DisplayName("標題")]
        [Required(ErrorMessage = "請輸入標題")]
        [MaxLength(60, ErrorMessage = "標題長度不能大於60個字元.")]
        public string Title { get; set; }


        [DisplayName("內容")]
        [Required(ErrorMessage = "請輸入內容")]
        [MaxLength(8000, ErrorMessage = "內容長度不能大於8000個字元.")]
        public string Content { get; set; }


        [DisplayName("作者")]
        [Required(ErrorMessage = "作者不可為空")]
        public string Author { get; set; }


        [DisplayName("建立時間")]
        public DateTime CreateDate { get; set; }


        [DisplayName("閱讀次數")]
        public int ClickCount { get; set; }
    }
}

 

 

 public ActionResult Create([Bind(Exclude="ZhengXingId")]ZhengXing zhengxing)
        {
            zhengxing.Author = Session["UserName"].ToString();
            zhengxing.CreateDate = DateTime.Now;
            if (ModelState.IsValid)
            {
                db.ZhengXings.Add(zhengxing);
                db.SaveChanges();
                return RedirectToAction("ManageIndex");
            }
            else
                return View(zhengxing);
        }

 

ZhengXing模型裡面有Title,Content,Author,CreateDate,ClickCount這幾個欄位,但是在create頁面僅僅給title和content賦值,並沒有給Author和CreateDate賦值,而是在後台賦值,但是每次ModelState.IsValid都為false,最後終於發現問題了,只要將模型裡的[Required(ErrorMessage = "作者不可為空")]注釋掉就行。

 

最終總結:ModelState.IsValid的驗證是在Submit後Action調用前進行模型驗證。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.