我有一些数据注释属性,如下所示:
[StringLength(20, MinimumLength = 5, ErrorMessage = "First name must be between 5 and 20 characters")]
Run Code Online (Sandbox Code Playgroud)
如何使用反射查找数据注释属性及其参数?
谢谢
我有一个ViewModel,它有一些DataAnnotations验证,然后对于更复杂的验证实现IValidatableObject并使用Validate方法.
我期待的行为是这样的:首先是所有DataAnnotations,然后,只有在没有错误的情况下,验证方法.我怎么发现这并非总是如此.我的ViewModel(演示版)有一个string,一个decimal和一个文件decimal?.所有这三个属性都只有Required属性.对于string和,decimal?行为是预期的行为,但对于decimal,当为空时,必需的验证失败(到目前为止很好),然后执行Validate方法.如果我检查属性,它的值为零.
这里发生了什么?我错过了什么?
注意:我知道必须使用Required属性来检查值是否为null.所以我希望被告知不要在不可空类型中使用Required属性(因为它不会触发),或者,某种程度上该属性理解POST值并注意该字段未被填充.在第一种情况下,属性不应该触发,并且应该触发Validate方法.在第二种情况下,属性应该触发,并且不应触发Validate方法.但我的结果是:属性触发器和Validate方法触发.
这是代码(没什么特别的):
控制器:
public ActionResult Index()
{
return View(HomeModel.LoadHome());
}
[HttpPost]
public ActionResult Index(HomeViewModel viewModel)
{
try
{
if (ModelState.IsValid)
{
HomeModel.ProcessHome(viewModel);
return RedirectToAction("Index", "Result");
}
}
catch (ApplicationException ex)
{
ModelState.AddModelError(string.Empty, ex.Message);
}
catch (Exception ex)
{
ModelState.AddModelError(string.Empty, "Internal error.");
}
return View(viewModel);
}
Run Code Online (Sandbox Code Playgroud)
模型:
public static HomeViewModel LoadHome()
{
HomeViewModel viewModel = new HomeViewModel();
viewModel.String = string.Empty;
return viewModel;
} …Run Code Online (Sandbox Code Playgroud) asp.net asp.net-mvc data-annotations asp.net-mvc-3 ivalidatableobject
我在MVC 3应用程序中创建了一个局部视图.此视图具有如下强类型模型:
public class ProductViewModel
{
[Required, Display(Name = "Product price")]
public decimal? ProductPrice
{
get;
set;
} ...
}
Run Code Online (Sandbox Code Playgroud)
在我的动作方法中,我像这样调用PartialView方法
PartialView("ProductViewModel", products[0]);
Run Code Online (Sandbox Code Playgroud)
但是在页面上我看不到验证逻辑的任何标记,如果页面上有任何错误,则没有任何反应.如果我将此局部视图用作编辑器模板,则可以正常工作.任何帮助表示赞赏.
编辑:更具体地说,我有一个HTML表单,我想通过ajax更新添加标记(如果用户点击一个按钮,我想在该表单中添加新标记).如果我静态地包含这些控件,我的意思是如果我在页面加载时渲染它们,验证工作,但如果我通过ajax调用向该表单添加控件,则不会为这些控件插入验证标记.我的局部视图看起来像这样:
@Html.LabelFor(x => x.ProductPrice)
@Html.TextBoxFor(x => x.ProductPrice)
@Html.ValidationMessageFor(x => x.ProductPrice)
Run Code Online (Sandbox Code Playgroud)
我的表单看起来像这样:
@using (Html.BeginForm())
{
<div id="div_Products">
@Html.EditorFor(x => x)
</div>
<input type="submit" value="Compare" />
}
Run Code Online (Sandbox Code Playgroud)
上面的代码效果很好,验证工作正常.在服务器端,我调用一个看起来像这样的动作方法:
[HttpPost]
public ActionResult InsertProduct()
{
var newProductVM = new ProductViewModel{ ProductPrice = 789 };
return PartialView("~/Views/Nutrition/EditorTemplates/ProductViewModel.cshtml", newProductVM);
}
Run Code Online (Sandbox Code Playgroud)
我发现MVC引擎只有在发现控件位于表单控件内时才会插入那些验证标记.当我尝试通过ajax调用更新我的表单控件时,MVC无法知道它们将被放置在表单元素中,这就是为什么它不会为它们发出任何验证逻辑,我想.
validation unobtrusive-javascript data-annotations asp.net-mvc-3
这是一个非常具体的问题.我设法通过使用名为EmailAddress.cshtml,保存在~/Views/Shared/EditorTemplates/文件夹中的编辑器模板自动将占位符属性添加到html5电子邮件输入类型.请参阅以下代码:
@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { @class = "text-box single-line", placeholder = ViewData.ModelMetadata.Watermark })
Run Code Online (Sandbox Code Playgroud)
它的工作原理是因为我[DataType(DataType.EmailAddress)]在视图模型中使用了DataAnnotation.
什么不起作用是我使用int?变量.
public class MiageQuotaRequestViewModel
{
[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "Nombre de place demandées", Prompt = "Nombre de place")]
[Range(0, 50, ErrorMessage = "La demande doit être comprise entre 0 et 50 places")]
public int? RequestedQuota { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
@Html.EditorFor 像这样翻译这个输入:
<input class="text-box single-line" data-val="true" data-val-number="The field Nombre de place demandées must be a number." data-val-range="La demande …Run Code Online (Sandbox Code Playgroud) c# placeholder mvc-editor-templates data-annotations asp.net-mvc-4
我有以下代码:
[Required(ErrorMessage = MessageModel.translateMessage("required")))]
[Display(Name= MessageModel.translateMessage("id"))]
public string user_id { get; set; }
Run Code Online (Sandbox Code Playgroud)
我试图使错误消息动态,但我在编译时得到错误:
"An attribute argument must be a constant expression , typeof expression or array creation expression of an attribute parameter type."
解决这个问题的任何方法?
我在我的视图模型中寻找一种方法来缩短搜索表单的查询字符串中的属性名称.例如,详细属性名称可能是查询,但您在查询字符串中看到q.
目前,我正在做以下事情来实现这一目标.
public string Query { get; set; }
public string q
{
get
{
return Query;
}
set
{
Query = value;
}
}
Run Code Online (Sandbox Code Playgroud)
我认为如果有数据注释来帮助解决这个问题可能会更容易.
[Querystring(Name="q")]
public string Query { get; set; }
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法来做到这一点,我没有想到或者是否有可能像我那样编写自己的数据注释?
我想创建自定义客户端验证器,但我希望通过业务逻辑层的Data Annotations属性定义验证规则.如何在运行时访问模型验证属性?
我想写'generator',它会转换这段代码:
public class LoginModel
{
[Required]
[MinLength(3)]
public string UserName { get; set; }
[Required]
public string Password { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
进入这一个:
var loginViewModel= {
UserName: ko.observable().extend({ minLength: 3, required: true }),
Password: ko.observable().extend({ required: true })
};
Run Code Online (Sandbox Code Playgroud)
但当然不是来自.cs来源.=)
也许反思?
UPD
我发现了这个方法:MSDN.但无法理解如何使用它.
我有一个引用自己的表,但我正在努力获得我想要的映射.我希望能够将儿童定义为拥有母亲,父亲和/或监护人的特定人的集合.守护者可能是父亲或母亲.
我希望能够看到人们被列入名单的人们可以浏览的树状图; 用户可以扩展一个人的节点以显示该人的所有孩子,而不管儿童定义的关系(母亲,父亲或监护人).
public partial class Person
{
[Key]
public int ID { get; set; }
[StringLength(100)]
public string Name { get; set; }
public int? GuardianID { get; set; }
[Column("MotherID")]
public int? MotherID { get; set; }
[Column("FatherID")]
public int? FatherID { get; set; }
[ForeignKey("MotherID")]
public virtual tblPerson Mother { get; set; }
[ForeignKey("FatherID")]
public virtual tblPerson Father { get; set; }
[ForeignKey("GuardianID")]
public virtual tblPerson Guardian { get; set; }
[InverseProperty("Guardian")]
[InverseProperty("Father")]
[InverseProperty("Mother")]
public virtual IEnumerable<tblPerson> …Run Code Online (Sandbox Code Playgroud) entity-framework fluent data-annotations self-referencing-table
我试图在MVC中使用HTML FileUpload控件上传文件.我想验证该文件只接受特定的扩展名.我已经尝试使用DataAnnotations命名空间的FileExtensions属性,但它不起作用.见下面的代码 -
public class FileUploadModel
{
[Required, FileExtensions(Extensions = (".xlsx,.xls"), ErrorMessage = "Please select an Excel file.")]
public HttpPostedFileBase File { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
在控制器中,我正在编写如下代码 -
[HttpPost]
public ActionResult Index(FileUploadModel fileUploadModel)
{
if (ModelState.IsValid)
fileUploadModel.File.SaveAs(Path.Combine(Server.MapPath("~/UploadedFiles"), Path.GetFileName(fileUploadModel.File.FileName)));
return View();
}
Run Code Online (Sandbox Code Playgroud)
在View中,我写了下面的代码 -
@using (Html.BeginForm("Index", "FileParse", FormMethod.Post, new { enctype = "multipart/form-data"} ))
{
@Html.Label("Upload Student Excel:")
<input type="file" name="file" id="file"/>
<input type="submit" value="Import"/>
@Html.ValidationMessageFor(m => m.File)
}
Run Code Online (Sandbox Code Playgroud)
当我运行应用程序并提供无效的文件扩展名时,它没有显示错误消息.我知道编写自定义验证属性的解决方案,但我不想使用自定义属性.请指出我哪里出错了.
我正在进行表格注册ApplicationUser.在那里,我有Email or phone像Facebook 这样的领域.我DataAnnotation用于模型验证.在Data annotation我获得[EmailAddress]电子邮件验证和[Phone]电话号码验证.但我需要类似的东西[EmailAddressOrPhone].那我怎么能实现呢?
public class RegisterViewModel
{
.....
[Required]
[Display(Name = "Email or Phone")]
public string EmailOrPhone { get; set; }
......
}
Run Code Online (Sandbox Code Playgroud) data-annotations ×10
c# ×7
asp.net-mvc ×6
asp.net ×2
validation ×2
.net ×1
attributes ×1
c#-4.0 ×1
file-upload ×1
fluent ×1
placeholder ×1
reflection ×1
regex ×1
viewmodel ×1