Bounty获奖后更新
一个新的解决方案正在解决这个问题.请参考ASP.NET MVC 3预览1:http://weblogs.asp.net/scottgu/archive/2010/07/27/introducing-asp-net-mvc-3-preview-1.aspx
查看模型验证改进部分,您将在其中看到我的问题的解决方案.
原帖
参考我之前的文章如何使用ASP.NET MVC 2验证两个属性,其中我问我如何比较模型验证的两个属性.
我确实觉得这个答案很有用,但我遇到了一个完全不同的问题:
问题:如果属性级ValidationAttribute包含错误,则不验证类级别ValidationAttributes.
请考虑以下事项:
[EqualTo("Email", "EmailConfirm", ErrorMessage = "E-mailadresserne skal være ens")]
[EqualTo("Password", "PasswordConfirm", ErrorMessage = "Adgangskoderne skal være ens")]
[Bind(Exclude="UserId")]
public class EditSiteUser
{
[Required(ErrorMessage="Du skal bekræfte adgangskode")]
public string PasswordConfirm { get; set; }
[Required(ErrorMessage="Du skal bekræfte e-mailadressen")]
[Email(ErrorMessage="Ugyldig e-mailadresse")]
public string EmailConfirm { get; set; }
public int UserId { get; set; }
[Required(ErrorMessage = "Du skal indtaste et brugernavn")]
public …Run Code Online (Sandbox Code Playgroud) validation asp.net-mvc data-annotations asp.net-mvc-3 asp.net-mvc-2
什么是DataAnnotations和应用程序验证块之间的区别?
在我的视图模型中,我有以下属性:
[Required]
[DataType(DataType.Date, ErrorMessage="Please enter a valid date in the format dd/mm/yyyy")]
[Display(Name = "Date of Birth")]
public DateTime DOB { get; set; }
Run Code Online (Sandbox Code Playgroud)
在我看来,我有以下几点:
<div class="editor-label">
@Html.LabelFor(model => model.DOB)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.DOB)
@Html.ValidationMessageFor(model => model.DOB)
</div>
Run Code Online (Sandbox Code Playgroud)
在提交表单之前,DOB的默认值是1/01/0001如何停止自动填充此值,我只想在人们访问此表单时使用空字段?
我在Silverlight 4应用程序中有一个简单的测试页面,我正在尝试获取自定义验证规则.
我有一个TextBox和一个Button,我在TextBlock中显示验证结果.我的视图模型有一个Name属性,它绑定了TextBox的Text属性.我在Name属性上有两个验证属性, [Required]和[CustomValidation].
当我点击提交按钮时,必需的验证器正确触发,但我的自定义验证器的验证方法内的断点永远不会被命中.我不明白为什么会这样,因为我认为我非常仔细地遵循了MS的例子:http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.customvalidationattribute(v = vs.95)的.aspx
以下是视图模型的代码:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using GalaSoft.MvvmLight.Command;
namespace MyProject
{
// custom validation class
public class StartsCapitalValidator
{
public static ValidationResult IsValid(string value)
{
// this code never gets hit
if (value.Length > 0)
{
var valid = (value[0].ToString() == value[0].ToString().ToUpper());
if (!valid)
return new ValidationResult("Name must start with capital letter");
}
return ValidationResult.Success;
}
}
// my view model
public class ValidationTestViewModel …Run Code Online (Sandbox Code Playgroud) 我有一个带有属性的视图模型,如下所示:
[Display(Name = "Some Property", Description = "This is description", Prompt = "This is prompt")]
[Required(ErrorMessage = RequiredFieldMessage)]
public string SomeProperty { get; set; }
Run Code Online (Sandbox Code Playgroud)
但这似乎没有在视图中呈现任何额外的内容.你需要做一些额外的工作吗?
<div class="editor-label">
@Html.LabelFor(model => model.SomeProperty )
</div>
<div class="editor-field">
@Html.TextAreaFor(model => model.SomeProperty , 5, 80, null)
@Html.ValidationMessageFor(model => model.SomeProperty )
</div>
Run Code Online (Sandbox Code Playgroud) 我看到有一些类似的问题,但没有一个能解决我的问题.
我正在使用Entity Framework 4.3开发MVC3应用程序.我有一个英国日期字段,我计划允许用户使用Jquery UI datepicker进行编辑(由于这个博客我得到了工作).
幸运的是,这个博客包含了使用英国格式制作日期选择器的说明,但是,EF验证仍然告诉我需要输入有效的日期格式.很奇怪,它并没有阻止我将日期提交给数据库,只是不显眼的验证开始并显示消息.
目前我有以下数据注释:
[DataType(DataType.Date)]
public System.DateTime Module_Date { get; set; }
Run Code Online (Sandbox Code Playgroud)
但我也试过添加:
[DisplayFormat(DataFormatString="{0:dd/MM/yyyy}")]
Run Code Online (Sandbox Code Playgroud)
这完全没有效果.我希望有人有一个解决方案,因为我不喜欢关闭不引人注意的验证来停止此错误消息.
谢谢
编辑
在@Iridio回答之后,我考虑添加一个模型绑定,实际上从像我这样读过它的几个帖子似乎是正确的做法,但我想出的并没有效果.这是我尝试过的:
public class DateTimeBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
var date = value.ConvertTo(typeof(DateTime), CultureInfo.CurrentCulture);
return date;
}
}
Run Code Online (Sandbox Code Playgroud)
Application_Start()在Global.asax.cs文件的方法中使用此方法:
ModelBinders.Binders.Add(typeof(DateTime), new DateTimeBinder());
ModelBinders.Binders.Add(typeof(DateTime?), new DateTimeBinder());
Run Code Online (Sandbox Code Playgroud) c# validation entity-framework data-annotations asp.net-mvc-3
我创建了一个单独的类库来保存我的所有模型对象.这是因为有两个站点,但需要相同的模型对象和随附的验证.而不是在两个地方复制和粘贴代码,我认为我可以添加到库中.除了MaxLength之外,一切看起来都很棒,当我添加System.ComponentModel.DataAnnotations时它不会显示出来
是的,我添加了一个参考,但似乎没有什么能像在Web解决方案中那样工作.
我[Display(Name ="name")]在属性中有一个带有set 的类,并且[Table("tableName"]在类的顶部.
现在我正在使用反射来获取这个类的一些信息,我想知道我是否能以某种方式[Display(Name ="name")]向类本身添加一个.
它会是这样的
[Table("MyObjectTable")]
[Display(Name ="My Class Name")] <-------------- New Annotation
public class MyObject
{
[Required]
public int Id { get; set; }
[Display(Name="My Property Name")]
public string PropertyName{ get; set; }
}
Run Code Online (Sandbox Code Playgroud) 如果我将数据注释添加到我的ViewModel,则DateTime字段的值始终为{1/1/0001 12:00:00 AM}.
视图模型
public class EditReleaseViewModel : BaseViewModel
{
[Display(Name = "ReleaseDate", ResourceType = typeof(SharedResource))]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd.MM.yyyy HH:mm}")]
[Required(ErrorMessageResourceName = "FieldRequired", ErrorMessageResourceType = typeof(SharedResource))]
public DateTime ReleaseDate { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
控制器非常简单,如果我删除数据注释并使用默认一切正常.
调节器
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(EditReleaseViewModel viewModel)
{
if (ModelState.IsValid)
{
...
}
}
Run Code Online (Sandbox Code Playgroud)
视图
<div class="form-group col-sm-12 col-md-6 col-lg-4">
<label asp-for="ReleaseDate" class="col-md-3 control-label"></label>
<div class="col-md-9">
<input asp-for="ReleaseDate" class="form-control" />
<span asp-validation-for="ReleaseDate" class="text-danger" />
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
它是一个ASP.NET核心MVC RC2应用程序 - 也许我在那里缺少一些东西.
我正在尝试使用ASP.NET Core MVC 2.1项目中的资源本地化来配置验证错误消息,如本文所述.
我想根据洋葱架构在我的项目中分离组件,模型是在一个单独的组件中.因此,模型名称空间与主机应用程序名称空间不同.如上所述这里,我呼吁通过完整的类型名称我的资源文件.
但是,不会根据资源文件替换模型属性的消息.
我究竟做错了什么?
模型:
using System.ComponentModel.DataAnnotations;
namespace LocalizedAspNetCoreApp.DomainModels
{
public class TestModel
{
[Display(Name = "Value")]
[Required(ErrorMessage = "ValueRequired")]
public string Value { get; set; }
}
}
Run Code Online (Sandbox Code Playgroud)
Sturtup.cs:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace LocalizedAspNetCoreApp.Host
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.AddDataAnnotationsLocalization();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment …Run Code Online (Sandbox Code Playgroud) data-annotations ×10
c# ×4
validation ×4
asp.net ×2
asp.net-core ×2
asp.net-mvc ×2
.net ×1
block ×1
html5 ×1
mvvm ×1
razor ×1
reflection ×1
resx ×1
silverlight ×1