我使用的是Asp.net MVC 4和.NET 4.5。我有一个视图,其中该类的名称,班级教师姓名和该班级中的学生列表以编辑模式显示。我的主要观点看起来像
public class Class
{
public int ClassId { get; set; }
public string ClassName { get; set; }
public string ClassTeacherName { get; set; }
[RequiredInList(FieldName = "LastName", ErrorMessageResourceType = typeof(ErrorMessagesResource), ErrorMessageResourceName = "Required")]
public List<Student> Students { get; set; }
}
我有学生
public partial class Student
{
public int StudentID { get; set; }
public string LastName { get; set; }
public string FirstMidName { get; set; }
public System.DateTime EnrollmentDate { get; set; }
public decimal RollNo { get; set; }
}
我的自定义属性为
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter, AllowMultiple = true)]
public class RequiredInListAttribute : RequiredAttribute
{
/// <summary>
/// Gets or sets the name.
/// </summary>
public string FieldName { get; set; }
/// <summary>
/// The is valid.
/// </summary>
/// <param name="value">
/// The value.
/// </param>
/// <param name="validationContext">
/// The validation context.
/// </param>
/// <returns>
/// The <see cref="ValidationResult"/>.
/// </returns>
/// <exception cref="InvalidOperationException">
/// Invalid operation exception
/// </exception>
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var val = value as IEnumerable;
if (value == null || val == null)
{
throw new InvalidOperationException("This attribute Required In List is intended to use only on list");
}
var isInvalidFiled =
(val.Cast<object>().Select(v => v.GetType().GetProperty(this.FieldName).GetValue(v, null))).Any(
property => property == null);
return !isInvalidFiled
? ValidationResult.Success
: new ValidationResult(string.Format(this.ErrorMessageString, "Last Name"), new[]{"Students[0].LastName"});
}
}
现在我的问题是在发布表单后,即使没有提供姓氏,也不会出现错误。
答案 0 :(得分:0)
将其放在您的CSHTML页面上:
@Html.ValidationSummary()
你也可以在cshtml中的每个字段之后使用这样的东西:
@Html.ValidationMessageFor(model => model.StudentID)