使い分けが面倒くさくないのModelBinderクラスASP.NET MVCプレビュー5
-
09-06-2019 - |
質問
するとプレビュー5以下にリリースノート:
るためのサポートを追加しましたカスタムモデルのバインダー.カスタムバインダーできますを定義する複雑な種類のパラメータとしてアクションへの方法です。この機能を使用するには、マーク、複合型またはパラメータ宣言【ModelBinder(...)].
だからどうやってく実際にこの装置を用いたいこの作品は私のコントローラ:
public ActionResult Insert(Contact contact)
{
if (this.ViewData.ModelState.IsValid)
{
this.contactService.SaveContact(contact);
return this.RedirectToAction("Details", new { id = contact.ID}
}
}
他のヒント
もっ。ASP.NET 普場所を登録するための実施IControlBinders.ものの基礎この新しいコントローラです。UpdateModel方法です。
私は基本的にはこれら二つの概念を実施IModelBinderるのと同じことをやるコントローラです。UpdateModelのためのすべての公共性のmodelClass.
public class ModelBinder : IModelBinder
{
public object GetValue(ControllerContext controllerContext, string modelName, Type modelType, ModelStateDictionary modelState)
{
object model = Activator.CreateInstance(modelType);
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(model);
foreach (PropertyDescriptor descriptor in properties)
{
string key = modelName + "." + descriptor.Name;
object value = ModelBinders.GetBinder(descriptor.PropertyType).GetValue(controllerContext, key, descriptor.PropertyType, modelState);
if (value != null)
{
try
{
descriptor.SetValue(model, value);
continue;
}
catch
{
string errorMessage = String.Format("The value '{0}' is invalid for property '{1}'.", value, key);
string attemptedValue = Convert.ToString(value);
modelState.AddModelError(key, attemptedValue, errorMessage);
}
}
}
return model;
}
}
おです。asax.csん追加する必要がありま
protected void Application_Start()
{
ModelBinders.Binders.Add(typeof(Contact), new ModelBinder());
所属していません StackOverflow