>  기사  >  백엔드 개발  >  MVC의 데이터 유효성 검사 예제 요약

MVC의 데이터 유효성 검사 예제 요약

零下一度
零下一度원래의
2017-06-24 09:44:141428검색

1. 일반적인 상황

MVC 프레임워크를 사용해 본 사람들이라면 MVC 데이터 검증에 익숙할 것입니다. 예를 들어 다음과 같은 모델이 있습니다.

1     public class UserInfo2     {3         [Required(ErrorMessage = "UserName不可为空1111")]4         public string UserName { get; set; }5         public string Sex { get; set; }6         public string Mobile { get; set; }7         public string Address { get; set; }8     }

Front end:

 1 @using (Html.BeginForm()) 
 2 { 3     @Html.AntiForgeryToken() 4     <div class="form-horizontal"> 5         <h4>UserInfo</h4> 6         <hr /> 7         @Html.ValidationSummary(true, "", new { @class = "text-danger" }) 8         <div class="form-group"> 9             @Html.LabelFor(model => model.UserName, htmlAttributes: new { @class = "control-label col-md-2" })10             <div class="col-md-10">11                 @Html.EditorFor(model => model.UserName, new { htmlAttributes = new { @class = "form-control" } })12                 @Html.ValidationMessageFor(model => model.UserName, "", new { @class = "text-danger" })13             </div>14         </div>15         <div class="form-group">16             @Html.LabelFor(model => model.Sex, htmlAttributes: new { @class = "control-label col-md-2" })17             <div class="col-md-10">18                 @Html.EditorFor(model => model.Sex, new { htmlAttributes = new { @class = "form-control" } })19                 @Html.ValidationMessageFor(model => model.Sex, "", new { @class = "text-danger" })20             </div>21         </div>22         <div class="form-group">23             @Html.LabelFor(model => model.Mobile, htmlAttributes: new { @class = "control-label col-md-2" })24             <div class="col-md-10">25                 @Html.EditorFor(model => model.Mobile, new { htmlAttributes = new { @class = "form-control" } })26                 @Html.ValidationMessageFor(model => model.Mobile, "", new { @class = "text-danger" })27             </div>28         </div>29         <div class="form-group">30             @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })31             <div class="col-md-10">32                 @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })33                 @Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })34             </div>35         </div>36         <div class="form-group">37             <div class="col-md-offset-2 col-md-10">38                 <input type="submit" value="Create" class="btn btn-default" />39             </div>40         </div>41     </div>42 }

효과:

예, MVC는 일부 속성에 특정 특성을 추가하여 데이터의 유효성을 검사할 수 있습니다. 이는 누구에게나 낯설지 않을 수 있습니다.

그거면 괜찮습니다.

2. 일반적인 상황

실제 개발에서는 대부분 EF 또는 기타 방법을 사용하여 데이터베이스의 모든 테이블이나 뷰가 코드에서 해당 클래스 모델을 갖도록 만듭니다. 한발 물러서서 이 클래스의 일부 속성에 일부 데이터 확인 기능을 추가하더라도 데이터베이스가 변경된 후 이러한 모델을 다시 생성하면 기능 이전에 추가한 확인이 사라지므로 어떻게 해결합니까? 이 문제?

가정:

1     public class UserInfo2     {    
3         public string UserName { get; set; }4         public string Sex { get; set; }5         public string Mobile { get; set; }6         public string Address { get; set; }7     }

UserInfo는 데이터베이스를 통해 생성된 모델입니다. 데이터베이스에서 생성된 모델을 수정해서는 안 됩니다. 하지만 즉, 이 모델의 특정 속성에 대해 데이터 확인을 수행해야 합니다. 예를 들어 UserName 속성에 대해 null이 아닌 확인을 수행해야 합니다.

누구나 일반적으로 부분 분류를 생각합니다. 네, 부분 분류를 통해 위의 문제를 해결할 수 있습니다.

먼저 모델의 클래스에 부분 키워드를 추가한 다음 이 모델의 부분 클래스를 작성합니다.

1     public partial class UserInfo2     {3         [Required(ErrorMessage = "UserName不可为空1111")]4         public string UserName { get; set; }5     }

그러나 이로 인해 오류가 발생합니다. 즉, 클래스에 중복된 속성이 있습니다. 예, 일부 클래스에서는 속성이 동일한 이름을 가질 수 없습니다. 그렇다면 우리는 무엇을 해야 할까요? MVC 프레임워크는 이미 솔루션을 제공했습니다.

다음과 같이 쓸 수 있습니다:

1     [MetadataType(typeof(MeteUserInfo))]2     public partial class UserInfo3     {4         private class  MeteUserInfo5         {6             [Required(ErrorMessage = "UserName不可为空1111")]7             public string UserName { get; set; }8         }9     }

이렇게 하면 위의 문제가 쉽게 해결될 것입니다.

위 내용은 MVC의 데이터 유효성 검사 예제 요약의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.