【问题标题】:How do you use the new ModelBinder classes in ASP.NET MVC Preview 5如何在 ASP.NET MVC Preview 5 中使用新的 ModelBinder 类
【发布时间】:2010-09-07 06:37:04
【问题描述】:

您会注意到 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}
    }
}

【问题讨论】:

    标签: asp.net-mvc


    【解决方案1】:

    嗯,我调查了这个。 ASP.NET 为注册 IControlBinders 的实现提供了一个公共位置。他们还通过新的 Controller.UpdateModel 方法获得了这项工作的基础知识。

    因此,我通过创建 IModelBinder 的实现,基本上结合了这两个概念,该实现与 Controller.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;
        }
    }
    

    在您的 Global.asax.cs 中,您需要添加如下内容:

    protected void Application_Start()
    {
        ModelBinders.Binders.Add(typeof(Contact), new ModelBinder());
    

    【讨论】:

      猜你喜欢
      • 2010-09-11
      • 2010-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多