I am using Asp.net MVC 4 and .NET 4.5. I have a view where Name of class, class teacher name and List of students in that class are displayed in edit mode. My main view looks like
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; }
}
where I have student as
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; }
}
and my custom attribute as
[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"});
}
}
now my problem is after posting the form, even if Last name is not provided, no error comes.
Put this on your CSHTML page:
@Html.ValidationSummary()
You can also use something like this after each field in the cshtml:
@Html.ValidationMessageFor(model => model.StudentID)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.