asp.net mvc 中的验证属性
我的模型是这样的:
public class Line
{
public int CatalogNumber {get; set;}
public int TeamCode {get; set;}
}
我有一个获取目录号和团队代码的视图,我想检查两件事:
- 我们的数据库中有这样的目录号
- 对于给定的团队有这样的目录号
我写了一个属性(派生自ValidationAttribute
),检查我们的数据库中是否存在这样的目录号。但它没有任何作用!
也许不可能用属性来进行这样的检查?
(我知道我可以实现 IValidable 并覆盖 IsValid 方法,但出于我自己的原因,我更喜欢使用属性来实现)。
我必须在没有 serverPost 的情况下做到这一点(ajax 会很好),
我真的很感激一个很好的例子来做到这一点。
ps(我们使用的是mvc3)
My model is something like this:
public class Line
{
public int CatalogNumber {get; set;}
public int TeamCode {get; set;}
}
I have a view that gets catalog number and a team code, And I want to check two things:
- there is such catalog number in our database
- There is such catalog number for the given team
I wrote an attribute (that derives from ValidationAttribute
) that checks if there is such a catalog number in our Data Base. But it does nothing!
Maybe it's impossible to such check with an attribute?
(I know that I can implement IValidable
and override IsValid
method but for my own reasons I prefer doing it with an attribue).
I've to do it without serverPost (ajax would be good)
I'll really appreciate a good example hot to do it.
p.s. (We are using mvc3)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为远程验证可以帮助您解决这个问题。您可以使用它来检查数据库中是否存在目录号:
然后在您的控制器中(我尚未测试此代码,但它应该是类似的内容):
我相信您还可以有其他字段,以便您可以检查目录号对于给定的团队代码是否有效(我认为团队代码必须可为空,因为用户在当前模型中输入目录号之前可能无法输入团队代码,因为不需要团队代码)。所以你的模型是:
控制器代码:
我希望这能为你指明解决方案的正确方向。
I think that Remote Validation could help you out with this problem. You could use it to check that the catalog number exists in the database:
Then in your controller (I haven't tested this code but it should be something along the lines of):
I believe you can also have additional fields so that you could check that the catalog number is valid for the given TeamCode (I think the TeamCode would have to be nullable as the user may not enter one before entering a catalog number in your current model as the team code is not required). So your model would be:
and the controller code:
I hope this points you in the right direction to a solution.