使用MVC Razor进行模型验证
本文关键字:模型 验证 MVC Razor 使用 | 更新日期: 2023-09-27 18:07:20
我正在使用Razor引擎实现基于MVC的网站。
我已经在模型中创建了验证。即学生验证如下:[MetadataType(typeof(Student.StudentMetaData))]
public partial class Student
{
internal sealed class StudentMetaData
{
[Required(ErrorMessageResourceName = "FirstNameRequired", ErrorMessageResourceType = typeof(StudentMessages))]
public object FirstName { set; get; }
[Required(ErrorMessageResourceName = "FatherNameRequired", ErrorMessageResourceType = typeof(StudentMessages))]
public object FatherName { set; get; }
}
}
学生已经实现IDataErrorInfo接口。数据字段存在于其他部分类中(由T4文件创建的部分类)。
问题是当我使用它与客户端验证在Razor
视图使用:
@Html.TextBoxFor(m => m.FatherName, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.FatherName)
它没有得到我在资源文件中指定的消息。
我以前用WPF尝试过同样的技术,它工作得很好。
我允许在Web中进行客户端验证。配置并在我的视图中使用:
@{
HtmlHelper.ClientValidationEnabled = true;
}
Add Name space in modal class in mvc.
using System.ComponentModel.DataAnnotations;
public class TelePhones
{
[Required (ErrorMessage = "MobileNo is required")]
public long MobileNo { get; set; }
[DisplayFormat(DataFormatString = "{0:dd MMM yyyy}")]
[DataType(DataType.Date)]
public string DateOfBirth { get; set; }
[Range(15, 70, ErrorMessage = "Price must be between 15 and 70")]
public int Age { get; set; }
}
client side validation in mvc
<div class="editor-label">
@Html.LabelFor(model => model.MobileNo)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.MobileNo)
@Html.ValidationMessageFor(model => model.MobileNo)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.DateOfBirth)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.DateOfBirth)
@Html.ValidationMessageFor(model => model.DateOfBirth)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Age)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Age)
@Html.ValidationMessageFor(model => model.Age)
</div>