asp.net-mvc ViewModel中使用的基本验证属性

示例

模型

using System.ComponentModel.DataAnnotations;

public class ViewModel
{
    [Required(ErrorMessage="Name is required")] 
    public string Name { get; set; }

    [StringLength(14, MinimumLength = 14, ErrorMessage = "Invalid Phone Number")]
    [Required(ErrorMessage="Phone Number is required")] 
    public string PhoneNo { get; set; }

    [Range(typeof(decimal), "0", "150")]
    public decimal? Age { get; set; }

    [RegularExpression(@"^\d{5}(-\d{4})?$", ErrorMessage = "无效的邮政编码。")]
    public string ZipCode {get;set;}

    [EmailAddress(ErrorMessage = "Invalid Email Address")] 
    public string Email { get; set; }

    [Editable(false)] 
    public string Address{ get; set; }
}

视图

// 在此处包括Jquery和无障碍Js,以进行客户端验证

@using (Html.BeginForm("Index","Home") { 

    @Html.TextBoxFor(model => model.Name) 
    @Html.ValidationMessageFor(model => model.Name)

    @Html.TextBoxFor(model => model.PhoneNo)
    @Html.ValidationMessageFor(model => model.PhoneNo)

    @Html.TextBoxFor(model => model.Age)
    @Html.ValidationMessageFor(model => model.Age)

    @Html.TextBoxFor(model => model.ZipCode)
    @Html.ValidationMessageFor(model => model.ZipCode)

    @Html.TextBoxFor(model => model.Email)
    @Html.ValidationMessageFor(model => model.Email)

    @Html.TextBoxFor(model => model.Address)
    @Html.ValidationMessageFor(model => model.Address)

    <input type="submit" value="submit" />
}

控制者

public ActionResult Index(ViewModel _Model) 
{ 
    // 检查所发布的表格是否有效。 
    if(ModelState.IsValid) 
    { 
        // 您的模型在这里有效。
        // 执行您需要执行的任何操作,例如数据库操作,
        // 和/或重定向到其他控制器和动作。
    }
    else 
    {
        // 重定向到同一操作
        return View(_Model);
    } 
}