【发布时间】:2014-03-19 13:00:43
【问题描述】:
我正在使用 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"});
}
}
现在我的问题是提交表格后,即使没有提供姓氏,也不会出现错误。
【问题讨论】:
-
...调试这段代码告诉你什么?调试时
isInvalidField的值是多少? -
isInvalidField 的值为 True。所以应该添加理想的验证消息。但它没有出现在视图中
-
验证消息添加在客户端还是服务器端?
-
服务器端。现在不需要客户端。
标签: c# asp.net asp.net-mvc validation asp.net-mvc-4