Asp.net MVC樣本項目“Suteki.Shop”分析之資料驗證

來源:互聯網
上載者:User

在Suteki.Shop,實現了自己的資料校正機制,可以說其設計思路還是很有借鑒價值的。而使用這種 機制也很容易在Model中對相應的實體物件(屬性)添加校正操作方法。下面就來介紹一下其實現方式。

首先,看一下這樣類圖:

在Suteki.Shop定 義一個“IValidatingBinder”介面,其派生自IModelBinder:

其介面中定義了一個 重載方法UpdateFrom,其要實現的功能與MVC中UpdateFrom一樣,就是自動讀取我們在form中定義的有些 元素及其中所包含的內容。

實現IValidatingBinder介面的類叫做:ValidatingBinder,下面是 其核心代碼說明。

首先是BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)該方法是在IModelBinder介面中定義的,是其核心功能,用於將 用戶端資料轉成我們希望Model類型。

public virtual void UpdateFrom(BindingContext bindingContext)
{
foreach (var property in bindingContext.Target.GetType ().GetProperties())
{
try
{
foreach (var binder in propertyBinders)
{
binder.Bind(property, bindingContext);
}
}
catch (Exception exception)
{
if (exception.InnerException is FormatException ||
exception.InnerException is IndexOutOfRangeException)
{
string key = BuildKeyForModelState(property, bindingContext.ObjectPrefix);
bindingContext.AddModelError(key, bindingContext.AttemptedValue, "Invalid value for {0}".With(property.Name));
bindingContext.ModelStateDictionary.SetModelValue(key, new ValueProviderResult(bindingContext.AttemptedValue, bindingContext.AttemptedValue, CultureInfo.CurrentCulture));
}
else if (exception is ValidationException)
{
string key = BuildKeyForModelState(property, bindingContext.ObjectPrefix);
bindingContext.AddModelError(key, bindingContext.AttemptedValue, exception.Message);
bindingContext.ModelStateDictionary.SetModelValue(key, new ValueProviderResult (bindingContext.AttemptedValue, bindingContext.AttemptedValue, CultureInfo.CurrentCulture));
}
else if (exception.InnerException is ValidationException)
{
string key = BuildKeyForModelState(property, bindingContext.ObjectPrefix);
bindingContext.AddModelError(key, bindingContext.AttemptedValue, exception.InnerException.Message);
bindingContext.ModelStateDictionary.SetModelValue(key, new ValueProviderResult (bindingContext.AttemptedValue, bindingContext.AttemptedValue, CultureInfo.CurrentCulture));
}
else
{
throw;
}
}

}
if (!bindingContext.ModelStateDictionary.IsValid)
{
throw new ValidationException("Bind Failed. See ModelStateDictionary for errors");
}
}

聯繫我們

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