基于用户角色的MVC3验证
我们使用 MVC3 进行无阻碍验证,一切都很好;我们的自定义验证既可以在服务器上也可以在客户端上运行。
我们还使用内置的 asp.net 角色提供程序。我们有用于不同角色的特定视图。根据登录用户的角色,某些字段(ViewModel 的属性)是必需的。
我的问题是:我们如何基于角色创建 ValidationAttribute ?当用户是普通用户时,我们想要使一个属性为Required;但当用户是管理员时,我们不希望将该字段设置为必填字段。但我们确实想使用相同的视图。
我知道我们可以创建一个自定义 ValidationAttribute (创建一个派生自 ValidationAttribute 的类),我想这对于服务器端验证来说效果很好。但我们确实想验证这个客户端。
我认为我们在上面的 ValidationAttribute 中实现了 IClientValidatable 并编写了一些 jQuery 来对服务器进行 Ajax 回调以检查当前登录的用户及其角色。 但这会让我们每次特定属性改变时都会进行一次Ajax调用,而登录的用户不会改变。
这样做的正确方法是什么?或者我们应该为不同的登录用户创建不同的ViewModel?
当我的上述解释没有意义时请告诉我,我可以在需要时添加一些示例代码。
任何帮助表示赞赏。
谢谢,
皮姆
We are using MVC3 with unobstructuve validation, all is fine; we got our custom validations working on the server as well as on the client.
We are also using the build-in asp.net Role provider. We have particular Views that we use for different Roles. Some of the fields (properties of the ViewModel) are Required based on the Role of the logged-in user.
My question is: How do we make a ValidationAttribute based on a Role? We want to make a property Required when the user is Normal User; but we don't want to make that field required when the user is an Administrator. But we do want to use the same view.
I know we can create a custom ValidationAttribute (creating a class that derives from ValidationAttribute) I suppose that will work fine for Server-Side validation. But we really want to validate this Client-Side.
I reckon we implement the IClientValidatable in our above ValidationAttribute and write some jQuery to make an Ajax call back to the server to check the current logged in user and its roles.
But this will make us do an Ajax call every time the specific property changes, and the logged-in user will not change.
What is the right way to do this? Or should we create different ViewModels for different logged in user?
Please let me know when my above explanation doesn't make sense, I can add some example code when needed.
Any help is appreciated.
Thanks,
Pim
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为您确实可以实现一个也实现 IClientValidatable 的自定义 ValidationAttribute。但是,您可以为客户端“重用”不显眼的必需验证:
这应该在输入上生成与 requiredAttribute 相同的不显眼的必需属性,但前提是满足您的条件。
I think you can indeed implement a custom ValidationAttribute that also implements the IClientValidatable. But then you could just "reuse" the unobtrusive required validation for the client side:
This should generate the same unobtrusive required attributes on the input as the RequiredAttribute, but only if your condition is met.