【问题标题】:Model Validation is not appearing in asp.net mvc模型验证未出现在 asp.net mvc 中
【发布时间】: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


【解决方案1】:

把它放在你的 CSHTML 页面上:

 @Html.ValidationSummary()

您也可以在 cshtml 中的每个字段之后使用类似这样的内容:

  @Html.ValidationMessageFor(model => model.StudentID)

【讨论】:

  • 您为什么不编辑您的问题并添加 CSHTML 文件?这会有所帮助。
猜你喜欢
  • 2015-02-26
  • 1970-01-01
  • 1970-01-01
  • 2011-12-24
  • 1970-01-01
  • 2011-04-04
  • 1970-01-01
  • 2010-11-18
  • 1970-01-01
相关资源
最近更新 更多