使用 Lightspeed 进行 MVC3 验证

发布于 2024-10-25 10:40:20 字数 1997 浏览 7 评论 0原文

我的 ORM (LightSpeed) 为动物表生成此表,其中包含名称和年龄。使用 MVC3 和 Razor

   [Serializable]
  [System.CodeDom.Compiler.GeneratedCode("LightSpeedModelGenerator", "1.0.0.0")]
  [System.ComponentModel.DataObject]
  [Table(IdColumnName="AnimalID", IdentityMethod=IdentityMethod.IdentityColumn)]
  public partial class Animal : Entity<int>
  {     
    [ValidatePresence]
    [ValidateLength(0, 50)]
    private string _name;

    [ValidateComparison(ComparisonOperator.GreaterThan, 0)]
    private int _age;

    public const string NameField = "Name";
    public const string AgeField = "Age";

    [System.Diagnostics.DebuggerNonUserCode]
    [Required] // ****I put this in manually to get Name required working
    public string Name
    {
      get { return Get(ref _name, "Name"); }
      set { Set(ref _name, value, "Name"); }
    }

    [System.Diagnostics.DebuggerNonUserCode]
    public int Age
    {
      get { return Get(ref _age, "Age"); }
      set { Set(ref _age, value, "Age"); }
    }

添加 [Required] 属性:

在此处输入图像描述

未添加 [Required] 属性:(注意 LightSpeed验证的奇怪渲染)

在此处输入图像描述

填写名称:

在此处输入图像描述

在上面的图像中 - 顶部的验证是 LightSpeed(放入 ValidationSummary),侧面是 MVC3(放入 ValidationMessageFor)

目前仅使用服务器端验证。

问题:如何让 LightSpeed 验证在 MVC3 中正常运行?

我认为这是这个领域的东西 http ://www.mindscapehq.com/staff/jeremy/index.php/2009/03/aspnet-mvc-part4/

对于服务器端验证 - 您将需要使用发出错误的自定义模型绑定器更准确地来自 LightSpeed 验证,而不是利用 DefaultModelBinder 行为。查看直接使用或改编 Mvc 社区代码库中的 EntityModelBinder

http://www.mindscapehq.com/forums/Thread.aspx?PostID=12051

My ORM (LightSpeed) generates this for Animals table, with Name and Age. Using MVC3 and Razor

   [Serializable]
  [System.CodeDom.Compiler.GeneratedCode("LightSpeedModelGenerator", "1.0.0.0")]
  [System.ComponentModel.DataObject]
  [Table(IdColumnName="AnimalID", IdentityMethod=IdentityMethod.IdentityColumn)]
  public partial class Animal : Entity<int>
  {     
    [ValidatePresence]
    [ValidateLength(0, 50)]
    private string _name;

    [ValidateComparison(ComparisonOperator.GreaterThan, 0)]
    private int _age;

    public const string NameField = "Name";
    public const string AgeField = "Age";

    [System.Diagnostics.DebuggerNonUserCode]
    [Required] // ****I put this in manually to get Name required working
    public string Name
    {
      get { return Get(ref _name, "Name"); }
      set { Set(ref _name, value, "Name"); }
    }

    [System.Diagnostics.DebuggerNonUserCode]
    public int Age
    {
      get { return Get(ref _age, "Age"); }
      set { Set(ref _age, value, "Age"); }
    }

With [Required] attribute added:

enter image description here

With no [Required] attribute added: (notice LightSpeed strange rendering of validation)

enter image description here

With name filled in:

enter image description here

In images above - the validation at the top is LightSpeed (put into ValidationSummary) and at the side is MVC3 (put into ValidationMessageFor)

Am only using Server Side validation currently.

Question: How do I get LightSpeed validation working well in MVC3?

I think it is something in this area http://www.mindscapehq.com/staff/jeremy/index.php/2009/03/aspnet-mvc-part4/

For the server side validation - you will want to use a custom model binder which emits the errors from LightSpeed validation more precisely rather than the leveraging the DefaultModelBinder behavior. Have a look at either directly using or adapting the EntityModelBinder from the community code library for Mvc

http://www.mindscapehq.com/forums/Thread.aspx?PostID=12051

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

雪落纷纷 2024-11-01 10:40:20

请参阅链接 http://www.mindscapehq.com/forums/Thread.aspx?ThreadID =4093

Jeremys的回答(Mindscape有很大的支持!)

public class EntityModelBinder2 : DefaultModelBinder
  {
    public static void Register(Assembly assembly)
    {
      ModelBinders.Binders.Add(typeof(Entity), new EntityModelBinder2());

      foreach (Type type in assembly.GetTypes())
      {
        if (typeof(Entity).IsAssignableFrom(type))
        {
          ModelBinders.Binders.Add(type, new EntityModelBinder2());
        }
      }
    }

    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
      object result = base.BindModel(controllerContext, bindingContext);

      if (typeof(Entity).IsAssignableFrom(bindingContext.ModelType))
      {
        Entity entity = (Entity)result;

        if (!entity.IsValid)
        {
          foreach (var state in bindingContext.ModelState.Where(s => s.Value.Errors.Count > 0))
          {
            state.Value.Errors.Clear();
          }

          foreach (var error in entity.Errors)
          {
            if (error.ErrorMessage.EndsWith("is invalid")) continue;
            bindingContext.ModelState.AddModelError(error.PropertyName ?? "Custom", error.ErrorMessage);
          }
        }
      }

      return result;
    }
  }

并在Global.asax中注册使用:

EntityModelBinder2.Register(typeof(MyEntity).Assembly);

Register 调用设置要用于模型装配中每个实体类型的模型绑定器,因此请根据需要进行修改。

See link http://www.mindscapehq.com/forums/Thread.aspx?ThreadID=4093

Jeremys answer (Mindscape have great support!)

public class EntityModelBinder2 : DefaultModelBinder
  {
    public static void Register(Assembly assembly)
    {
      ModelBinders.Binders.Add(typeof(Entity), new EntityModelBinder2());

      foreach (Type type in assembly.GetTypes())
      {
        if (typeof(Entity).IsAssignableFrom(type))
        {
          ModelBinders.Binders.Add(type, new EntityModelBinder2());
        }
      }
    }

    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
      object result = base.BindModel(controllerContext, bindingContext);

      if (typeof(Entity).IsAssignableFrom(bindingContext.ModelType))
      {
        Entity entity = (Entity)result;

        if (!entity.IsValid)
        {
          foreach (var state in bindingContext.ModelState.Where(s => s.Value.Errors.Count > 0))
          {
            state.Value.Errors.Clear();
          }

          foreach (var error in entity.Errors)
          {
            if (error.ErrorMessage.EndsWith("is invalid")) continue;
            bindingContext.ModelState.AddModelError(error.PropertyName ?? "Custom", error.ErrorMessage);
          }
        }
      }

      return result;
    }
  }

and in Global.asax register using:

EntityModelBinder2.Register(typeof(MyEntity).Assembly);

The Register call sets up the model binder to be used for each entity type in your model assembly so modify as required.

思慕 2024-11-01 10:40:20

从 2011 年 4 月 4 日起,您可以使用 Lightspeed 夜间版本进行客户端验证。

创建验证器提供程序如下:

public class LightspeedModelValidatorProvider : DataAnnotationsModelValidatorProvider
{
    private string GetDisplayName(string name)
    {
        return name; //  go whatever processing is required, eg decamelise, replace "_" with " " etc
    }

    protected override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context, IEnumerable<Attribute> attributes)
    {

        if(typeof(Entity).IsAssignableFrom(metadata.ContainerType))
        {
            List<Attribute> newAttributes = new List<Attribute>(attributes);
            var attr = DataAnnotationBuilder.GetDataAnnotations(metadata.ContainerType, metadata.PropertyName, GetDisplayName(metadata.PropertyName));
            newAttributes.AddRange(attr);

            return base.GetValidators(metadata, context, newAttributes);
        }

        return base.GetValidators(metadata, context, attributes);
    }
}

然后在 Application_Start() 中添加

        ModelValidatorProviders.Providers.Clear();
        ModelValidatorProviders.Providers.Add(new LightspeedModelValidatorProvider());

You can get client side validation working with Lightspeed nightly builds from 04/04/2011 onwards.

Create a validator provider as follows:

public class LightspeedModelValidatorProvider : DataAnnotationsModelValidatorProvider
{
    private string GetDisplayName(string name)
    {
        return name; //  go whatever processing is required, eg decamelise, replace "_" with " " etc
    }

    protected override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context, IEnumerable<Attribute> attributes)
    {

        if(typeof(Entity).IsAssignableFrom(metadata.ContainerType))
        {
            List<Attribute> newAttributes = new List<Attribute>(attributes);
            var attr = DataAnnotationBuilder.GetDataAnnotations(metadata.ContainerType, metadata.PropertyName, GetDisplayName(metadata.PropertyName));
            newAttributes.AddRange(attr);

            return base.GetValidators(metadata, context, newAttributes);
        }

        return base.GetValidators(metadata, context, attributes);
    }
}

Then in Application_Start() add

        ModelValidatorProviders.Providers.Clear();
        ModelValidatorProviders.Providers.Add(new LightspeedModelValidatorProvider());
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文