标签: data-annotations

自定义模型 - 粘合剂,从cookie问题?

我正在尝试执行以下操作.

使用默认模型绑定器从查询字符串值绑定对象.
如果失败,我会尝试从cookie值绑定对象.

但是我在这个对象上使用dataannotations,我遇到了以下问题.

  1. 如果没有查询字符串参数,则默认模型绑定程序甚至不会在必填字段上注册任何验证错误.如果属性本身不在查询字符串集合中,它显然甚至不会触发这些验证器.我该如何改变这种行为?如果它们不在查询字符串中,我希望必填字段是错误的.
  2. 如果我确实有模型验证错误,我想从cookie加载模型然后重新验证对象.我不知道如何让模型绑定器验证我自己填充的对象.

这是我到目前为止所拥有的.

    public class MyCarBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var myCar = base.BindModel(controllerContext, bindingContext);

        if (!bindingContext.ModelState.IsValid)
        {
            myCar = MyCar.LoadFromCookie();
            // Not sure what to do to revalidate
        }

        return myCar;
    }
}
Run Code Online (Sandbox Code Playgroud)

任何有关如何正确执行此操作的帮助将不胜感激.

asp.net-mvc model-binding data-annotations

2
推荐指数
1
解决办法
1532
查看次数

ASP.Net MVC 3 - 使用DataAnnotations进行不显眼的客户端验证 - 字段是必需的,但不应该是

我在MVC 3中使用客户端,不引人注意的验证.我有一个名为MinPrice的字段,仅使用DisplayName和Range属性进行修饰.但它没有通过客户端验证说"MinPrice字段是必需的".我不知道为什么,我绝对没有任何地方应用的必需属性.

    [DisplayName("Asking Price")]
    [Range(0, 99999999, ErrorMessage="Invalid number")]
    public int MinPrice { get; set; }
Run Code Online (Sandbox Code Playgroud)

是什么造成的?

(注意:我可以在html源代码中看到data-val-required ="Minprice字段是必需的"属性,因此与新的不显眼的例程有关的事情就是把它放在那里).我似乎没有其他领域的这个问题..

data-annotations unobtrusive-validation asp.net-mvc-3

2
推荐指数
1
解决办法
1521
查看次数

如何将DataAnnotations持久保存到ViewModel

在我的应用程序中,我的模型结构用DataAnnotations修饰.这有助于我的验证完美,但是我不确定如何在没有双重输入的情况下将这些DataAnnotations保留到我的ViewModel.

基本上我很懒,我试图尽可能保持干燥.

class User
{
    [Required]
    public string FirstName {get; set; }
    [Required]
    public string LastName {get; set; }
    public datetime RegistrationDate {get; }
}

class CreateUserViewModel
{
    public string FirstName {get; set; }
    public string LastName {get; set; }    
}
Run Code Online (Sandbox Code Playgroud)

第一个类永远不会被View使用,但它包含应用程序所需的所有DataAnnotations.第二个类总是由CreateUser View使用,但我不想重新应用DataAnnotations.这可能吗?如果是这样,怎么样?

asp.net-mvc data-annotations

2
推荐指数
1
解决办法
690
查看次数

派生的RequiredAttribute不起作用

我正在尝试实现自己的RequiredAttribute,我在其中调用自定义资源处理程序:

public class LocalizedValidationAttributes
{
    public class LocalizedRequiredAttribute : RequiredAttribute
    {
        private String _resourceString = String.Empty;

        public new String ErrorMessage
        {
            get { return _resourceString; }
            set { _resourceString = GetMessageFromResource(value); }
        }
    }

    private static String GetMessageFromResource(String resourceTag)
    {
        return ResourceManager.Current.GetResourceString(resourceTag);
    }

}
Run Code Online (Sandbox Code Playgroud)

我用以下方式调用它:

[LocalizedValidationAttributes.LocalizedRequiredAttribute(ErrorMessage = "test")]
public String Text { get; set; }
Run Code Online (Sandbox Code Playgroud)

但是从不调用ErrorMessage的getter.

任何提示?谢谢!

.net c# asp.net-mvc data-annotations asp.net-mvc-2

2
推荐指数
1
解决办法
861
查看次数

我可以创建一个采用值类型或引用类型但总是返回可为空类型的通用方法吗

这是我的方法。请注意,我将为泛型参数返回等效的可空类型R

    public static Nullable<R> GetValue<T, R>(this T a, Expression<Func<T, R>> expression)
        where T : Attribute
        where R : struct
    {
        if (a == null)
            return null;

        PropertyInfo p = GetProperty(expression);
        if (p == null)
            return null;

        return (R)p.GetValue(a, null);
    }
Run Code Online (Sandbox Code Playgroud)

我可以在调用中使用它来获取如下属性的值:

//I don't throw exceptions for invalid or missing calls 
//because I want to chain the calls together:
int maximumLength4 = instance.GetProperty(x => x.ToString())
                            .GetAttribute<StringLengthAttribute>()
                            .GetValue(x => x.MaximumLength)
                            .GetValueOrDefault(50);
Run Code Online (Sandbox Code Playgroud)

我想对字符串使用相同的通用方法:

//I'd like to use the GetValue generic method …
Run Code Online (Sandbox Code Playgroud)

c# generics reflection data-annotations

2
推荐指数
1
解决办法
1440
查看次数

Validator.TryValidateObject不验证属性

使用WebApi v2我已经构建了一个以对象为参数的东西.我正在使用IValidateableObject和dataannotations进行模型验证,我使用WebApi过滤器触发.

但是,一个对象包含所有需要验证的项目数组.我已经创建了一个自定义属性,以便使用像Asp.net Web Api嵌套模型验证这样做,但我无法进行验证.另外 - 我已经使用了ValidateAllProperties标志.

所以我构建了一个控制台应用程序来验证行为,似乎没有触发验证(或者我错误地调用了API).这是对我不起作用的东西:

namespace ConsoleApplication1 {using System; 使用System.Collections.Generic; 使用System.ComponentModel.DataAnnotations;

class Program
{
    static void Main()
    {
        var s = new Boundary { LowerDecimal = 1.1m };
        var isValid = Validator.TryValidateObject(s, new ValidationContext(s, null, null), new List<ValidationResult>(), true);
        Console.WriteLine("Validation resulted in " + isValid);
        Console.ReadLine();
    }
}

public class Boundary
{
    [Range(0,1)]
    public decimal LowerDecimal { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

}

isValid始终返回true.我在这做错了什么?

编辑 - 也尝试像这里定义MetaData类:当我使用Validator.TryValidateObject时,验证不起作用

c# validation data-annotations asp.net-web-api

2
推荐指数
1
解决办法
6359
查看次数

为什么DataType.Password仅在服务器端验证?

我有模特儿

[Required]
[EmailAddress]
[Remote("EmailValidation", "Account", ErrorMessage = "{0} already has an account, please enter a different email address.")]
[Display(Name = "Email")]
public string Email { get; set; }

[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }

[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[System.ComponentModel.DataAnnotations.Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
Run Code Online (Sandbox Code Playgroud)

和注册表格:

<form …
Run Code Online (Sandbox Code Playgroud)

.net c# validation asp.net-mvc data-annotations

2
推荐指数
1
解决办法
1万
查看次数

使用ViewModel中的DataAnnotations在ASP.NET MVC中进行日期验证

我的页面的ViewModel中有一个DateTime属性.我想知道是否有内置的检查用户输入有效日期的方法.

以下是我当前代码的样子,截至目前,它不会自动确保用户输入有效日期(只需要验证):

ViewModel属性:

[Required]
[DataType(DataType.Date)]
public DateTime MyDate{ get; set; }
Run Code Online (Sandbox Code Playgroud)

Razor MVC6观点:

<label asp-for="MyDate" class="control-label"></label>
<input asp-for="MyDate" class="form-control" />
<span asp-validation-for="MyDate" class="text-danger" />
Run Code Online (Sandbox Code Playgroud)

c# asp.net asp.net-mvc data-annotations unobtrusive-validation

2
推荐指数
1
解决办法
4448
查看次数

在剃刀视图中显示枚举描述

我有一个枚举属性的模型如下:

namespace ProjectManager.Models
{
    public class Contract
    {
        .....
        public enum ContractStatus
        {
            [System.ComponentModel.Description("????")]
            New,
            [System.ComponentModel.Description("?? ?????? ??????")]
            WaitForPayment,
            [System.ComponentModel.Description("?????? ???")]
            Paid,
            [System.ComponentModel.Description("????? ?????")]
            Finished
        };

        public ContractStatus Status { get; set; }
        .....
    }

}
Run Code Online (Sandbox Code Playgroud)

在我的剃刀视图中,我想显示每个项目的枚举描述,例如,????而不是New.我试着按照这个答案中的说明,但我不知道在哪里添加扩展方法以及如何在我的razor视图文件中调用扩展方法.如果有人能完成我的代码,我将感激不尽:

@model IEnumerable<ProjectManager.Models.Contract>
....
<table class="table">
    <tr>
        .....
        <th>@Html.DisplayNameFor(model => model.Status)</th>
        .....
    </tr>

@foreach (var item in Model) {
    <tr>
        ......
        <td>
            @Html.DisplayFor(modelItem => item.Status)  //<---what should i write here?
        </td>
        ....
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.Id …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-mvc enums data-annotations razor

2
推荐指数
1
解决办法
3115
查看次数

使用DataAnnotation的ASP.NET MVC Core仅日期格式不起作用

viewmodel视图中使用的跟随应该显示为StartDate,例如9/30/2015。但它显示为9/30/2015 12:00:00 AM。我怎样才能使它不显示时间,同时使用 DataAnnotaion?我知道我只能使用@Model.StartDate.ToString("MM/dd/yyy")内部视图显示日期。但这意味着您必须在使用以下各项的每个视图中执行此操作ViewModel

ViewModel

...
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime StartDate { get; set; }
...
Run Code Online (Sandbox Code Playgroud)

更新

上面相应的模型类ViewModel已经具有以下内容DataAnnotation,可以在SQL Server表中正确创建数据类型为Date;并且当您在其中的相应表上运行查询时,SSMS它会正确显示StartDate列的数据(仅包含日期,例如9/30/2015等)。

模型

...
[DataType(DataType.Date)]
public DateTime StartDate { get; set; }
...
Run Code Online (Sandbox Code Playgroud)

实际上,sql db中的StartDate Date仅是。此外,如果我对其执行查询,SSMS则仅正确返回日期。

data-annotations asp.net-mvc-viewmodel asp.net-core

2
推荐指数
1
解决办法
4833
查看次数