如何在不使用mvc 4中的模型的情况下进行客户端验证

How to do Client side validation without using model in mvc 4

本文关键字:情况下 模型 验证 客户端 mvc      更新时间:2023-09-26

我正在开发一个ASP.NET MVC 4应用程序,在该应用程序中我没有使用视图模型,也不想使用它们。对于模型,我使用的是从实体生成的类。请告诉我有什么办法可以做到这一点。

您需要指定验证属性(如果您希望ASP为您处理验证)。您可以使用分部类来扩展您的模型,然后添加如下属性:

//this is the model (generated from the entities)  
   [MetadataType(typeof(User_Validation))]
    public partial class User
    {
    }

然后指定验证属性。

    public class User_Validation
    {
        [Required(ErrorMessage="The Full Name is required")]
        public string FullName{ get; set; }
        [Required(ErrorMessage="The Cellphone Number  is required")]
        public string CellNumber { get; set; }
    }

或者,您可以使用jQuery或您选择的其他客户端插件自行处理所有验证。

使用jQuery验证属性装饰表单元素(通常由MVC在读取模型的DataAnnotations时自动完成)。

从文档中,这就是如何进行简单的文本框验证:

<input id="cname" name="name" size="25" class="required" minlength="2" />

然后,

$(document).ready(function(){ $("#commentForm").validate(); });

有关更多的信息,请参阅jQuery验证文档