4

Preview 5 のリリース ノートには、次の内容が含まれています。

カスタム モデル バインダーのサポートが追加されました。カスタム バインダーを使用すると、複雑な型をアクション メソッドのパラメーターとして定義できます。この機能を使用するには、複合型またはパラメーター宣言を [ModelBinder(…)] でマークします。

では、この機能を実際に使用して、コントローラーでこのようなものを機能させるにはどうすればよいですか。

public ActionResult Insert(Contact contact)
{
    if (this.ViewData.ModelState.IsValid)
    {
        this.contactService.SaveContact(contact);

        return this.RedirectToAction("Details", new { id = contact.ID}
    }
}
4

1 に答える 1

2

さて、私はこれを調べました。ASP.NET は、IControlBinders の実装を登録するための共通の場所を提供します。また、新しい Controller.UpdateModel メソッドを介して、この機能の基本も備えています。

そこで、modelClass のすべてのパブリック プロパティに対して Controller.UpdateModel と同じことを行う IModelBinder の実装を作成することで、これら 2 つの概念を基本的に組み合わせました。

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;
    }
}

Global.asax.cs に、次のようなものを追加する必要があります。

protected void Application_Start()
{
    ModelBinders.Binders.Add(typeof(Contact), new ModelBinder());
于 2008-08-29T16:55:37.690 に答える