简体   繁体   English

绕过客户端验证MVC 3

[英]Bypass client side validation mvc 3

This is the model which we are using... 这是我们正在使用的模型...

Public Class Person
{
        [Display(ResourceType = typeof(BasicTags), Name = "FirstName")]
        [Required(ErrorMessageResourceName = "FirstNameRequired", ErrorMessageResourceType = typeof(BasicErrors))]
        public string FirstName;

        [Display(ResourceType = typeof(BasicTags), Name = "LastName")]
        [Required(ErrorMessageResourceName = "LastNameRequired", ErrorMessageResourceType = typeof(BasicErrors))]
        public string LastName;
}

Both the fields are set as required true. 这两个字段均根据需要设置为true。 Now we have another developer using this same Model in another view, he doesn`t want this validation for his page, how to skip the validation in the server side and before saving? 现在我们有另一个开发人员在另一个视图中使用相同的模型,他不希望页面进行此验证,如何在服务器端以及保存之前跳过验证?

The database fields are set as allow null. 数据库字段设置为allow null。

ViewData.ModelState.Remove("FirstName") 
ViewData.ModelState.Remove("LastName")

This only removes the client side message but the actual validation still remains. 这只会删除客户端消息,但实际的验证仍然保留。 Is there any way, so that I can save. 有什么办法,以便我可以保存。

Thanks. 谢谢。

您应该创建一个具有这些属性但没有针对特定页面的验证注释的自定义视图模型。

Simply don't check ModelState.IsValid on the server side and save your data. 只需不检查服务器端的ModelState.IsValid并保存您的数据即可。

HOWEVER - I would just make a copy of that view model, remove your attributes and be done with it. 但是,我只需要复制该视图模型,删除您的属性即可完成。 A ViewModel is for a View - if you have a different view, the standard thing to do is create a new Model. ViewModel用于视图-如果您具有其他视图,则标准操作是创建一个新的Model。 However - its your app - so the solution to do what you wanted is above. 但是-它是您的应用-因此上面要做您想要的解决方案。

If you are worried about the client side validation, then you have to create your own handler for the submit function and don't check if its valid - just post. 如果您担心客户端验证,则必须为Submit函数创建自己的处理程序,而不必检查其是否有效-只需发布即可。 Another hack. 另一个hack。 So - again.. try not to do it this way. 所以-再次..尽量不要这样做。 : ) :)

You can also call ModelState.Remove("FirstName"); 您还可以调用ModelState.Remove("FirstName");

Before ModelState.IsValid and it will do the trick, Like ModelState.IsValid之前,它将完成任务,就像

ModelState.Remove("FirstName");
if(ModelState.IsValid){
     // your code
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM