Asp.net mvc 3 在“我的”中自动显示年龄;“创建表单”;
我在我的创建表单中有生日和年龄字段,我想在填写生日后自动计算和显示年龄 所以我使用EntityFramework的CodeFirst和MVC3Razor视图 这是我的模型:Asp.net mvc 3 在“我的”中自动显示年龄;“创建表单”;,asp.net-mvc-3,razor,model,attributes,Asp.net Mvc 3,Razor,Model,Attributes,我在我的创建表单中有生日和年龄字段,我想在填写生日后自动计算和显示年龄 所以我使用EntityFramework的CodeFirst和MVC3Razor视图 这是我的模型: namespace Payroll_System.Models { public class Employee { [DataType(DataType.Date)] [DisplayName("Date of Birth:")] [Required(ErrorMessage =
namespace Payroll_System.Models
{
public class Employee
{
[DataType(DataType.Date)]
[DisplayName("Date of Birth:")]
[Required(ErrorMessage = "Birth Date is Required.")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0;dd/MM/yyyy}"
, NullDisplayText = "No Date of Birth is Selected.")]
public DateTime BirthDate { get; set; }
[Integer]
[Min(1, ErrorMessage = "Unless you are Benjamin Button.")]
public int Age
{
get
{
DateTime now = DateTime.Today;
int age = now.Year - BirthDate.Year;
if (BirthDate > now.AddYears(-age)) age--; ;
return age;
}
}
在我创建了模型之后,我使用MVC脚手架创建了带有CRUD选项的控制器。然后在Create的partialview中没有年龄文本框。因此,请提供一些代码。您无法输入值,更不用说验证只读属性了 您可能希望通过实现接口来验证数据 型号:
public class PersonFromSO : IValidatableObject
{
[DataType(DataType.Date)]
[DisplayName("Date of Birth:")]
[Required(ErrorMessage = "Birth Date is Required.")]
[DisplayFormat(ApplyFormatInEditMode = true,
DataFormatString = "{0;dd/MM/yyyy}",
NullDisplayText = "No Date of Birth is Selected.")]
public DateTime BirthDate { get; set; }
public int Age
{
get
{
DateTime now = DateTime.Today;
int age = now.Year - BirthDate.Year;
if (BirthDate > now.AddYears(-age)) age--; ;
return age;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext context)
{
if (Age < 1)
yield return new ValidationResult("You were born in the future.",
new[] { "Age" });
}
}
我会注意到这有点复杂,你最好直接验证出生日期
get
{
DateTime now = DateTime.Today;
int age = now.Year - BirthDate.Year;
if (BirthDate > now.AddYears(-age)) age--; ;
return age;
}
如果您还存储了时间,则这是错误的,它应该是下面的代码
get
{
DateTime now = DateTime.Now;
int age = now.Year - BirthDate.Year;
if (BirthDate > now.AddYears(-age)) age--; ;
return age;
}
你怎么能期望用户在只读属性中输入她的年龄?您可能会在“显示”视图中找到它,而不是在“创建”或“编辑”视图中。另外,什么是
[Integer]
和[Min]
属性,只读属性的验证点是什么?这是我的第一个MVC答案-我希望我做得不错。
get
{
DateTime now = DateTime.Today;
int age = now.Year - BirthDate.Year;
if (BirthDate > now.AddYears(-age)) age--; ;
return age;
}
get
{
DateTime now = DateTime.Now;
int age = now.Year - BirthDate.Year;
if (BirthDate > now.AddYears(-age)) age--; ;
return age;
}