在MVC中驗證表單資料

來源:互聯網
上載者:User

  在MVC中驗證表單資料方法有多種:錯誤匯總顯示,在每個驗證的表單元素後顯示等。www.asp.net/mvc網站上有教程。

  (以Northwind的Product表為例,資料和對象使用ADO.NET Entity Data Model自動產生)

  當使用一個表單添加一個Models.Product對象到資料庫時,我們在當前Controlle中建立一個Create方法來實現,此方法接受一個Models.Product類型的參數,

在將建立新產品的時候DefaultModelBinder會將表單中的值轉換成Models.Product對象,

DefaultModelBinder方法預設會檢查當前類(在這裡也即是Models.Product)是否繼承IDataErrorInfo介面,當類繼承了IDataErrorInfo介面時,類的每個屬性會調用IDataErrorInfo的的索引器,如果當前索引器返回錯誤,the model binder 會自動將錯誤寫入到model state,Controller類的ModelState中的錯誤在介面中使用Html.ValidationSummary()來顯示。

  DefaultModelBinder還會檢測IDataErrorInfo.Error屬性,此屬性工作表示的是與當前類相關的非屬性特性驗證錯誤。

範例程式碼:

 

Code
public partial class Product:IDataErrorInfo
    {

        private Dictionary<string, string> _errors = new Dictionary<string, string>();

        partial void OnProductNameChanging(string value)
        {
            if (string.IsNullOrEmpty(value))
                _errors.Add("ProductName", "ProductName is required.");
        }

        IDataErrorInfo 成員#region IDataErrorInfo 成員

        public string Error
        {
            get { return String.Empty; }
        }

        public string this[string columnName]
        {
            get
            {
                if (_errors.ContainsKey(columnName))
                {
                    return _errors[columnName].ToString();
                }
                else
                {
                    return string.Empty;
                }
            }
        }

        #endregion
    }

 

 

聯繫我們

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