熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> .NET編程 >> 正文

ASP.NET MVC 4框架揭秘:Action的執行(1)[2]

2022-06-13   來源: .NET編程 

  如下面的代碼片段所示綁定到參數上的數據具有三個來源HTTPPOST FormRouteData的Values和DataTokens屬性它們都是字典結構的數據集合如果參數類型為字符串或者簡單的值類型我們可以直接根據參數名稱和Key進行匹配對於復雜類型(比如之前例子中定義的包含Controller和Action名稱的數據類型SimpleModel)則通過反射根據類型創建新的對象並根據屬性名稱與Key的匹配關系對相應的屬性進行賦值

  public class DefaultModelBinder : IModelBinder

  {

  public object BindModel(ControllerContext controllerContext

  stringmodelName Type modelType)

  {

  if (modelTypeIsValueType || typeof(string) == modelType)

  {

  object instance;

  if (GetValueTypeInstance(controllerContext modelName

  modelType out instance))

  {

  return instance;

  };

  returnActivatorCreateInstance(modelType)

  }

  objectmodelInstance = ActivatorCreateInstance(modelType)

  foreach (PropertyInfo property in modelTypeGetProperties())

  {

  if (!propertyCanWrite || (!propertyPropertyTypeIsValueType

  &&propertyPropertyType!=typeof(string)))

  {

  continue;

  }

  objectpropertyValue;

  if (GetValueTypeInstance(controllerContext propertyName

  propertyPropertyType out propertyValue))

  {

  propertySetValue(modelInstance propertyValue null)

  }

  }

  returnmodelInstance;

  }

  private  boolGetValueTypeInstance(ControllerContext controllerContext

  stringmodelName Type modelType out object value)

  {

  var form = HttpContextCurrentRequestForm;

  string key;

  if (null != form)

  {

  key = formAllKeysFirstOrDefault(k =>stringCompare(k

  modelName true) ==

  if (key != null)

  {

  value =  ConvertChangeType(form[key] modelType)

  return true;

  }

  }

  key = controllerContextRequestContextRouteDataValues

  Where(item =>stringCompare(itemKey modelName true) ==

  Select(item =>itemKey)FirstOrDefault()

  if (null != key)

  {

  value = ConvertChangeType(controllerContextRequestContext

  RouteDataValues[key] modelType)

  return true;

  }

  key = controllerContextRequestContextRouteDataDataTokens

  Where(item =>stringCompare(itemKey modelName true) ==

  Select(item =>itemKey)FirstOrDefault()

  if (null != key)

  {

  value = ConvertChangeType(controllerContextRequestContext

  RouteDataDataTokens[key] modelType)

  return true;

  }

  value = null;

  return false;

  }

  }

       返回目錄ASPNET MVC 框架揭秘

       編輯推薦

       ASP NET開發培訓視頻教程

       Microsoft NET框架程序設計視頻教程

       Java程序性能優化讓你的Java程序更快更穩定

       Visual C++音頻/視頻技術開發與實戰

[]  []  


From:http://tw.wingwit.com/Article/program/net/201311/16105.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.