我想使用下面的代码为新用户创建一个视图模型。 “User”类仅包含我将保留到数据库的两个属性(目前已简化);视图模型添加了一个“比较密码”字段,该字段仅在视图中使用。我更喜欢让视图模型直接使用“User”类,而不是重复“User”中定义的所有字段。
我的问题是如何在“ComparePassword”字段的 [Compare] 属性中正确引用“User.Password”?
public class User
{
[Required]
public string UserName { get; set; }
[Required]
[DisplayName("Password")]
[DataType(DataType.Password)]
public string Password { get; set; }
}
public class NewUserViewModel
{
public User User { get; set; }
[Required]
[DataType(DataType.Password)]
[DisplayName("Re-enter Password")]
[Compare("Password", ErrorMessage="Passwords must match")]
public string ComparePassword { get; set; }
}
为“Password”和“ComparePassword”生成的 HTML 如下。
<input class="text-box single-line password"
data-val="true"
data-val-required="The Password field is required."
id="User_Password"
name="User.Password"
type="password" value="" />
<input class="text-box single-line password"
data-val="true"
data-val-equalto="Passwords must match"
data-val-equalto-other="*.Password"
data-val-required="The Re-enter Password field is required."
id="ComparePassword"
name="ComparePassword"
type="password" value="" />
关键是如何“数据值等于其他" 由 Javascript 处理。如果我使用 "Password" or "用户密码“没有任何反应 - 不执行任何检查。如果我使用”用户密码“检查已执行但总是失败。
直接在 jQuery 中执行此操作没有任何实际问题,但如果可能的话,我更愿意使用 [Compare] 属性。
刚刚通过 StackOverflow 和 Microsoft Connect 找到了答案:
See:
http://connect.microsoft.com/VisualStudio/feedback/details/665793/jquery-unobtrusive-validate-equalto-fails-with-compare-attribute http://connect.microsoft.com/VisualStudio/feedback/details/665793/jquery-unobtrusive-validate-equalto-fails-with-compare-attribute
and
JQuery 1.5 破坏了比较验证(JQuery Validate 1.8) https://stackoverflow.com/questions/5117458/jquery-1-5-breaks-compare-validate-jquery-validate-1-8
总而言之,它看起来像是 MVC3 附带的 jquery.validate.unobtrusive 文件中的一个错误。解决方法是更改 jquery.validate.unobtrusive 文件中的以下行。
element = $(options.form).find(":input[name=" + fullOtherName + "]")[0];
to
element = $(options.form).find(":input[name=" + fullOtherName.replace(".", "\\.") + "]")[0];
在 Microsoft Connect 上,它说 MS 已修复它,但我找不到新版本的链接。无论如何,这同时对我有用。希望能帮助到你
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)