在 MVC3 中使用远程验证时的空值
我在远程验证方面遇到问题。
我有一个视图模型,其属性上添加了远程验证器,但是当我运行表单并在文本框中输入字符串时,传递给控制器的值为空。
视图模型中的属性如下所示:
[Required(ErrorMessage = "Enter the host's name")]
[Remote("ValidateHostFullName", "BoardroomBooking", ErrorMessage = "Enter a different name")]
[DisplayName("Host's Name")]
public string HostFullName { get; set; }
控制器中验证器的代码如下所示:
public ActionResult ValidateHostFullName([Bind(Prefix="BookingReceptionViewModel")]string HostFullName)
{
if (!HostFullName.Equals("John Smith"))
{
return Json(true, JsonRequestBehavior.AllowGet);
}
return Json("{0} is not allowed", JsonRequestBehavior.AllowGet);
}
无论在框中键入什么内容,HostFullName 的字符串值都显示为 null。我已经尝试过使用和不使用绑定前缀,这没有什么区别。
我已经在模型上尝试过这个方法并且它有效,但似乎只有当我使用视图模型时才会出现问题。
谢谢马克
I am having a problem with remote validation.
I have a viewmodel with a property on which I have added a Remote validator but when I run the form and enter a string in the text box the value passed to the controller is null.
The property in the viewmodel looks like this:
[Required(ErrorMessage = "Enter the host's name")]
[Remote("ValidateHostFullName", "BoardroomBooking", ErrorMessage = "Enter a different name")]
[DisplayName("Host's Name")]
public string HostFullName { get; set; }
The code for the validator in the Controller looks like this:
public ActionResult ValidateHostFullName([Bind(Prefix="BookingReceptionViewModel")]string HostFullName)
{
if (!HostFullName.Equals("John Smith"))
{
return Json(true, JsonRequestBehavior.AllowGet);
}
return Json("{0} is not allowed", JsonRequestBehavior.AllowGet);
}
The value of the string for HostFullName shows as null no matter what is typed in the box. I have tried it with and without the Bind Prefix and that makes no difference.
I've tried this on a model and it works, it only seems to have an issue when I use a viewmodel.
Thanks
Mark
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我也有同样的问题。传入
ValidateHostFullName()
的参数必须与输入名称相同。I was having the same issue. The parameter coming into
ValidateHostFullName()
must be the same as the input name.我也有同样的问题。渲染的 html 控件没有以类名作为前缀,但在远程验证代码中,我通过添加 classname.propertyname 前缀进行绑定。删除这个绑定解决了我的问题。或者仅添加属性名称前缀也适合我。
I had the same problem. The rendered html control was NOT prefixed by class name but in remote validation code, I had binded by prefixing the classname.propertyname. Removing this binding solved my problem. Or else by prefixing only property name also works fine for me.