如何实现MVC数据验证-创新互联
这篇文章将为大家详细讲解有关如何实现MVC数据验证,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
一、一般情况
对于使用过MVC框架的人来说,对MVC的数据验证不会陌生,比如,我有一个Model如下:
public class UserInfo { [Required(ErrorMessage = "UserName不可为空1111")] public string UserName { get; set; } public string Sex { get; set; } public string Mobile { get; set; } public string Address { get; set; } }
前端:
@using (Html.BeginForm()) { @Html.AntiForgeryToken()UserInfo
@Html.ValidationSummary(true, "", new { @class = "text-danger" })@Html.LabelFor(model => model.UserName, htmlAttributes: new { @class = "control-label col-md-2" })@Html.EditorFor(model => model.UserName, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.UserName, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.Sex, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Sex, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Sex, "", new { @class = "text-danger" })