我想利用Validator.TryValidateValue()但不了解机制.说,我有以下内容:
public class User {
[Required(AllowEmptyStrings = false)]
[StringLength(6)]
public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
和方法:
public void CreateUser(string name) {...}
Run Code Online (Sandbox Code Playgroud)
我的验证码是:
ValidationAttribute[] attrs = bit of reflection here to populate from User class
var ctx = new ValidationContext(name, null, null);
var errors = new List<ValidationResult>();
bool valid = Validator.TryValidateValue(name, ctx, errors, attrs);
Run Code Online (Sandbox Code Playgroud)
它工作正常,直到值name是null.我ArgumentNullException在实例化时得到ValidationContext并且不明白为什么.TryValidateValue()还要求非空上下文.我有一个值和一个要验证的属性列表.这是ValidationContext为了什么?
我RangeValidator在我的模型中有一个属性,只允许0到100之间的整数.我有一个部分视图,显示一个表单,通过jQuery UI对话框更新属性.我查看了源代码,可以确认正确生成了数据注释属性.但是,验证无法正常工作.它确实执行某种验证,但它没有使用我设置的范围.值1,10和100不会产生错误.任何其他单个或两个数字值都会产生错误.但是,如果我用零填充,所有小于100的值都可以.
模型:
public class MyModel
{
...
[Required(ErrorMessage = "{0} is required")]
[Range(typeof(int), "0", "100",
ErrorMessage = "{0} can only be between {1} and {2}")]
public int Percentage { get; set; }
...
}
Run Code Online (Sandbox Code Playgroud)
局部视图:
@model MyApp.Models.Partials.MyModel
<div id="myDialog" class="editModal" title="Update Percentage">
@using (Ajax.BeginForm("UpdatePercentage", "MyController",
new AjaxOptions() { HttpMethod = "Post",
OnSuccess = "onUpdateSuccess" },
new { name = "myForm" }))
{
@Html.ValidationSummary(null, new { style = "width:auto;max-width:22em;
float:left;clear:both;" })
<div style="width:auto;float:left;clear:both;">
<div style="width:10em;float: left;text-align:right;clear:left;">
@Html.Label("Percentage:")
</div> …Run Code Online (Sandbox Code Playgroud) asp.net-mvc jquery-ui asp.net-mvc-validation data-annotations asp.net-mvc-3
有一种方法可以将默认资源设置为数据注释验证吗?
我不想做这样的事情:
[Required(ErrorMessage="Name required.", ErrorMessageResourceType=typeof(CustomDataAnnotationsResources)]
public string Name { get; set; }
Run Code Online (Sandbox Code Playgroud)
我想要这样的东西:
Global.asax中
DataAnnotations.DefaultResources = typeof(CustomDataAnnotationsResources);
Run Code Online (Sandbox Code Playgroud)
然后
[Required]
public string Name { get; set; }
Run Code Online (Sandbox Code Playgroud)
有人给我一个光!
提前致谢
编辑
我真正的问题是使用EF Code First CTP4.CTP5修复它.谢谢大家.
.net asp.net-mvc-2-validation data-annotations asp.net-mvc-2
我是数据注释的新手.我想知道是否有可能(以及如何)动态添加一些验证.解释原因非常广泛,但我有一个ViewModel在创建时接收和反对.在那个对象中,我必须检查一些属性,并根据其值,我应该有或没有一些验证.
一个例子:
public class ProfileViewModel
{
[Required(ErrorMessage = "The field {0} is required")]
[Display(Name = "Client Code")]
public int ClientCode { get; set; }
[Required(ErrorMessage = "The field {0} is required")]
[StringLength(100, ErrorMessage = "The field {0} must have up to 100 characters.")]
[Display(Name = "Company")]
public string Company { get; set; }
[StringLength(50, ErrorMessage = "The field {0} must have up to 50 characters.")]
[Display(Name = "Name")]
public string Name { get; set; }
[StringLength(50, ErrorMessage = "The field …Run Code Online (Sandbox Code Playgroud) 我想使用下面的代码为新用户创建一个视图模型."User"类只包含我将持久保存到数据库的两个属性(现在简化); 视图模型添加"比较密码"字段,该字段仅在视图中使用.我更喜欢让视图模型直接使用"User"类,而不是重复"User"中定义的所有字段.
我的问题是如何在"ComparePassword"字段的[Compare]属性中正确引用"User.Password"?
public class User
{
[Required]
public string UserName { get; set; }
[Required]
[DisplayName("Password")]
[DataType(DataType.Password)]
public string Password { get; set; }
}
public class NewUserViewModel
{
public User User { get; set; }
[Required]
[DataType(DataType.Password)]
[DisplayName("Re-enter Password")]
[Compare("Password", ErrorMessage="Passwords must match")]
public string ComparePassword { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
为"密码"和"ComparePassword"生成的HTML如下所示.
<input class="text-box single-line password"
data-val="true"
data-val-required="The Password field is required."
id="User_Password"
name="User.Password"
type="password" value="" />
<input class="text-box single-line password"
data-val="true"
data-val-equalto="Passwords must match"
data-val-equalto-other="*.Password"
data-val-required="The Re-enter …Run Code Online (Sandbox Code Playgroud) 我怎样才能告诉我的控制器/模型解析日期时应该具备哪种文化?
我正在使用这篇文章的一些内容将jquery datepicker实现到我的mvc应用程序中.
当我提交日期时,它"在翻译中丢失"我没有使用美国格式的日期,所以当它被发送到我的控制器时它只是变为空.
我有一个用户选择日期的表单:
@using (Html.BeginForm("List", "Meter", FormMethod.Get))
{
@Html.LabelFor(m => m.StartDate, "From:")
<div>@Html.EditorFor(m => m.StartDate)</div>
@Html.LabelFor(m => m.EndDate, "To:")
<div>@Html.EditorFor(m => m.EndDate)</div>
}
Run Code Online (Sandbox Code Playgroud)
我为此创建了一个编辑模板,以实现jquery datepicker:
@model DateTime
@Html.TextBox("", Model.ToString("dd-MM-yyyy"), new { @class = "date" })
Run Code Online (Sandbox Code Playgroud)
然后我创建像这样的datepicker小部件.
$(document).ready(function () {
$('.date').datepicker({ dateFormat: "dd-mm-yy" });
});
Run Code Online (Sandbox Code Playgroud)
这一切都很好.
这是问题的起点,这是我的控制器:
[HttpGet]
public ActionResult List(DateTime? startDate = null, DateTime? endDate = null)
{
//This is where startDate and endDate becomes null if the dates dont have the expected formatting.
}
Run Code Online (Sandbox Code Playgroud)
这就是为什么我想以某种方式告诉我的控制器应该期待什么样的文化?我的模特错了吗?我可以以某种方式告诉它使用哪种文化,比如数据注释属性? …
validation data-annotations jquery-ui-datepicker asp.net-mvc-3
我们管理几个ASP.NET MVC客户端网站,它们都使用如下的数据注释来验证客户电子邮件地址(为了便于阅读,我没有在此处包含正则表达式):
[Required(ErrorMessage="Email is required")]
[RegularExpression(@"MYREGEX", ErrorMessage = "Email address is not valid")]
public string Email { get; set; }
Run Code Online (Sandbox Code Playgroud)
我想要做的是集中这个正则表达式,这样如果我们对它进行更改,所有站点都会立即进行更改,我们不必在每个站点中手动更改它.
问题是数据注释的正则表达式参数必须是常量,所以我不能在运行时分配我从配置文件或数据库中检索到的值(这是我的第一个想法).
任何人都可以帮助我找到一个聪明的解决方案 - 或者失败,这是一种可以实现相同目标的替代方法吗?或者这只是要求我们编写一个专业的自定义验证属性,它将接受非常量值?
我正在使用Entity Framework 4.1开发一个ASP.Net MVC 3 Web应用程序,我对使用数据注释进行表单验证感到困惑.我总是将ViewModel返回给View而不是传递实际对象,因为我意识到这是不好的做法.例如:
public class ViewModelTeam
{
public Team Team { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我的观点可能会有这样的东西
@model UI.ViewModels.ViewModelTeam
@Html.HiddenFor(model => model.Team.teamID)
<div class="editor-label">
@Html.LabelFor(model => model.Team.description)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Team.description)
@Html.ValidationMessageFor(model => model.Team.description)
</div>
Run Code Online (Sandbox Code Playgroud)
为了验证这个View,我在部分类中创建了数据注释,就像这样
[MetadataType(typeof(TeamMetaData))]
public partial class Team
{
public class TeamMetaData
{
[DisplayName("Team Name")]
[Required(ErrorMessage = "Please enter a Team Name")]
public object description { get; set; }
Run Code Online (Sandbox Code Playgroud)
然后在我的创建控制器中我有这个
[HttpPost]
public ActionResult Create(Team team)
{
if (ModelState.IsValid)
{
//Add team and redirect …Run Code Online (Sandbox Code Playgroud) 我有一个名为SizeUS的带小数属性的POCO.我想使用数据注释来格式化视图中的小数显示.我的SizeUS属性在我的视图中只显示2个小数位,我希望它显示4个小数位.完成此操作的正确数据注释是什么?
[DisplayFormat( ? )]
public decimal SizeUS {get; set;}
Run Code Online (Sandbox Code Playgroud) 我正在搞乱数据注释.当我点击链接转到某个页面时,会显示验证消息,但我希望验证消息不显示,除非已发布数据.
视图:
@Html.TextBoxFor(m => m.EmailAddress, new { @placeholder = "Enter Email", @class = "form-control" })
@Html.ValidationSummary(true, "Registration Failed. Check your credentials")
@Html.ValidationMessageFor(m => m.EmailAddress, "You must enter a valid Email Address.")
Run Code Online (Sandbox Code Playgroud)
模型:
[Required(ErrorMessage = "Email is required")]
[DataType(DataType.EmailAddress)]
[EmailAddress]
[Display(Name = "Email Address: ")]
public string EmailAddress { get; set; }
Run Code Online (Sandbox Code Playgroud)
控制器:
[HttpGet]
public ActionResult AddUser()
{
return View();
}
[HttpPost]
public ActionResult AddUser(UserCreateViewModel user)
{
if (ModelState.IsValid)
{
var success = UserRepository.AddUser(user);
if (success)
{
return View("Success");
}
} …Run Code Online (Sandbox Code Playgroud) c# asp.net-mvc asp.net-mvc-validation data-annotations razor
data-annotations ×10
validation ×4
asp.net-mvc ×3
.net ×2
c# ×2
dynamic ×2
.net-4.0 ×1
asp.net ×1
jquery-ui ×1
passwords ×1
poco ×1
razor ×1
regex ×1
viewmodel ×1