ASP.NET MVC 如何加入 PartialCLass & DataAnnotations


  1. 說明
    1. 如何加入 PartialCLass & DataAnnotations
    2. 常用的 Model DataAnnotations
      1. 日期範圍驗證
      2. 更多的 DataType

筆記 ASP.NET MVC 如何替 EntityFramework Model 加入 Partial Class 從而讓前後端可以針對資料的 Input / Ouput 有型別檢驗以及輸出格式一致設定的方式。

logo

說明

如何加入 PartialCLass & DataAnnotations

/Models/PartialClass/ClassNamePartial.cs

using System.ComponentModel.DataAnnotations;

[MetadataType(typeof(classNamePartial))]
public partial class originalClassName {}
public class classNamePartial
{
  [Required]
  [Display(Name = "partialName")]
  public string property { get; set; }
}

/Models/context.tt/className.edmx/ClassName.cs

public partial class originalClassName
{
    public string property { get; set; }
}

常用的 Model DataAnnotations

[Display]
**[DisplayName]**:設定顯示名稱
**[DisplayFormat(ConvertEmptyStringToNull = true, NullDisplayText = “[Null]”)]**:Null 字串的替代顯示方式
**[StringLength]**:設定字串長度限制
**[Required]**:設定該欄位為「必要輸入」

[Display(Name = "產品名稱")]
[Required]
[Stringlength(32, ErrorMessage = "{0}的長度需介於{2}至{1}", MinimumLength = 8)]
public string Product {get; set;}

**[Range]**:設定數值範圍

[Display(Name = "庫存")]
[Range(0, 32, ErrorMessage = "{0}值範圍必須介於{1}至{2}")]
public int UnitsInStock {get; set;}

**[Key]**:明確的指定Primary Key, 取代 Id 的 convention

**[ScaffoldColumn(false)]**: 在基架中不要顯示該欄位

**[Compare(“AnotherPropertyName”)]**: 與其他的屬性值比較,使用情境第二次輸入密碼

日期範圍驗證

**[Range DateTime]**:設定日期範圍

[Range(typeof(Datetime), "2020/2/1", "2020/2/29")]
public DateTime SellEndDate {get; set;}

搭配 Chrome 瀏覽器預設的 DateTimePicker,會發生判斷失效的問題。可以藉由在 View 中 Override validator.methods.range 來修正:

@section Scripts {
  <script src="~/Scripts/jquery.validate.min.js"></script>
  <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

  <script>
      $.validator.methods.range = function (value, element, param) {
          if ($(element).attr('data-val-date')) {
              var min = $(element).attr('data-val-range-min');
              var max = $(element).attr('data-val-range-max');
              var date = new Date(value).getTime();
              var minDate = new Date(min).getTime() || 0;
              var maxDate = new Date(max).getTime() || 8640000000000000;
              return this.optional(element) || (date >= minDate && date <= maxDate);
          }
          // use the default method
          return this.optional(element) || (value >= param[0] && value <= param[1]);
      };
  </script>
}

Stackoverflow - DateTime client-side validation fails due to formatting

更多的 DataType

  • [CreditCard]
  • [EmailAddress]
  • [EnumData]
  • [FileExtensions]
  • [Phone]
  • [Url]