首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

ASP.NET MVC ValueProvider 體系第一篇:IValueProvider、ValueProviderResult 與 NameValueCollectionValueProvider

     編輯:關於ASP.NET

IValueProvider 核心介面

public interface IValueProvider
{
    bool ContainsPrefix(string prefix); // 判斷資料源是否含指定前綴
    ValueProviderResult GetValue(string key); // 依鍵取值,鍵為繫結上下文名稱(含前綴)
}

key 與資料源實際鍵可能不同(資料源鍵含前綴),ContainsPrefix 用於前置檢查。

ValueProviderResult:值封裝與型別轉換

[Serializable]
public class ValueProviderResult
{
    public ValueProviderResult(object rawValue, string attemptedValue, CultureInfo culture);
    public object ConvertTo(Type type); // 使用內部 Culture 轉換
    public virtual object ConvertTo(Type type, CultureInfo culture); // 指定文化轉換
    public string AttemptedValue { get; } // 原始字串表示(供顯示)
    public CultureInfo Culture { get; }
    public object RawValue { get; } // 原始物件(如 string[])
}

NameValueCollectionValueProvider:表單/查詢字串核心提供者

public class NameValueCollectionValueProvider : IUnvalidatedValueProvider, IEnumerableValueProvider, IValueProvider
{
    public NameValueCollectionValueProvider(NameValueCollection collection, CultureInfo culture);
    public virtual bool ContainsPrefix(string prefix);
    public virtual IDictionary<string, string> GetKeysFromPrefix(string prefix);
    public virtual ValueProviderResult GetValue(string key);
    public virtual ValueProviderResult GetValue(string key, bool skipValidation); // 跳過驗證
}

實作介面說明

  • IEnumerableValueProvider:擴充 GetKeysFromPrefix 回傳前綴符合的鍵值字典,支援集合繫結索引枚舉。
  • IUnvalidatedValueProvider:提供 GetValue(key, skipValidation),允許繫結時略過請求驗證(如允許 HTML 內容)。

NameValueCollection 特性與多值行為

  • 允許相同鍵多值(Add("foo", "1"); Add("foo", "2"))。
  • GetValue("foo").RawValue 回傳 string[]。
  • ConvertTo(int[]) → 逐元素轉換為 int[];ConvertTo(int) → 僅取第一個元素。

FormValueProvider 與 QueryStringValueProvider

兩者皆繼承 NameValueCollectionValueProvider,分別包裝 Request.Form 與 Request.QueryString。HttpFileCollectionValueProvider 雖繼承 DictionaryValueProvider,但邏輯類似處理多檔案。

總結

IValueProvider 定義資料存取契約,ValueProviderResult 封裝原始值與文化相關轉換。NameValueCollectionValueProvider 為表單/查詢字串核心實作,支援多值、集合鍵枚舉與無驗證讀取。掌握此基礎可自訂 Provider 整合任意鍵值資料來源。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved