>  기사  >  백엔드 개발  >  MVC 데이터 검증 예제 소개 공유

MVC 데이터 검증 예제 소개 공유

零下一度
零下一度원래의
2017-06-15 13:48:22955검색

이 글은 주로 MVC 데이터 검증 관련 정보를 자세하게 소개하고 있으며, 이는 특정 참고 가치가 있습니다. 관심 있는 친구들은 참고하시기 바랍니다.

1. 일반적인 상황

MVC 프레임워크를 사용해 본 분들에게는 전혀 낯설지 않습니다. 예를 들어 MVC 데이터 유효성 검사에는 다음과 같은 모델이 있습니다.


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()
  <p class="form-horizontal">
    <h4>UserInfo</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <p class="form-group">
      @Html.LabelFor(model => model.UserName, htmlAttributes: new { @class = "control-label col-md-2" })
      <p class="col-md-10">
        @Html.EditorFor(model => model.UserName, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.UserName, "", new { @class = "text-danger" })
      </p>
    </p>
    <p class="form-group">
      @Html.LabelFor(model => model.Sex, htmlAttributes: new { @class = "control-label col-md-2" })
      <p class="col-md-10">
        @Html.EditorFor(model => model.Sex, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.Sex, "", new { @class = "text-danger" })
      </p>
    </p>
    <p class="form-group">
      @Html.LabelFor(model => model.Mobile, htmlAttributes: new { @class = "control-label col-md-2" })
      <p class="col-md-10">
        @Html.EditorFor(model => model.Mobile, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.Mobile, "", new { @class = "text-danger" })
      </p>
    </p>
    <p class="form-group">
      @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })
      <p class="col-md-10">
        @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })
      </p>
    </p>
    <p class="form-group">
      <p class="col-md-offset-2 col-md-10">
        <input type="submit" value="Create" class="btn btn-default" />
      </p>
    </p>
  </p>
}

효과:

예, MVC는 일부 속성을 전달할 수 있습니다. 특정 기능을 추가합니다. 데이터를 확인하세요. 이는 누구에게나 낯설지 않을 수 있습니다.

이대로라면 괜찮습니다.

2. 일반적인 상황

실제 개발에서는 대부분 EF나 다른 방법을 사용하여 데이터베이스의 모든 테이블이나 view에 해당 클래스 model을 코드에 포함시킵니다. 한발 물러서서 이 클래스의 일부 속성에 일부 데이터 확인 기능을 추가하더라도 데이터베이스가 변경된 후 이러한 모델을 다시 생성하면 확인 기능이 사라지기 전에 추가한 것입니다. , 그렇다면 이 문제를 어떻게 해결해야 할까요?

가정:


public class UserInfo
  {  
    public string UserName { get; set; }
    public string Sex { get; set; }
    public string Mobile { get; set; }
    public string Address { get; set; }
  }

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

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

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


public partial class UserInfo
  {
    [Required(ErrorMessage = "UserName不可为空1111")]
    public string UserName { get; set; }
  }

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

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


[MetadataType(typeof(MeteUserInfo))]
  public partial class UserInfo
  {
    private class MeteUserInfo
    {
      [Required(ErrorMessage = "UserName不可为空1111")]
      public string UserName { get; set; }
    }
  }

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

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

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