绕过客户端验证 mvc 3
这是我们正在使用的模型...
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;
}
这两个字段都设置为必需的 true。现在我们有另一个开发人员在另一个视图中使用相同的模型,他不想对其页面进行此验证,如何在服务器端和保存之前跳过验证?
数据库字段设置为允许为空。
ViewData.ModelState.Remove("FirstName")
ViewData.ModelState.Remove("LastName")
这只会删除客户端消息,但实际验证仍然保留。有什么办法可以救救我吗?
谢谢。
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. 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.
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您应该创建一个具有这些属性但没有针对该特定页面的验证注释的自定义视图模型。
You should make a custom View Model that has these properties but doesn't have their validation annotations for that specific page.
只需不在服务器端检查 ModelState.IsValid 并保存数据即可。
但是 - 我只会复制该视图模型,删除您的属性并完成它。 ViewModel 用于视图 - 如果您有不同的视图,标准要做的就是创建一个新模型。但是 - 它是您的应用程序 - 因此执行您想要的操作的解决方案在上面。
如果您担心客户端验证,那么您必须为提交函数创建自己的处理程序,并且不检查其是否有效 - 只需发布。另一个黑客。所以-再次..尽量不要这样做。 :)
Simply don't check ModelState.IsValid on the server side and save your data.
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. 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. Another hack. So - again.. try not to do it this way. : )
您还可以
在
ModelState.IsValid
之前调用ModelState.Remove("FirstName");
,它会起到作用,就像You can also call
ModelState.Remove("FirstName");
Before
ModelState.IsValid
and it will do the trick, Like