我正在创建一个表单,以便网站的成员可以更改其帐户的密码,并且我想显示一条消息,说明用户在填写字段时所犯的错误(例如密码太短,至少需要非字母数字字符等)。我想在字段名称旁边的同一页面中显示这些消息。这是我的代码:
@helper RenderForm()
{
<form method="post">
<p>Change your password below</p>
<div><label for="currentPassword">Current Password</label>
<input type="password" id="currentPassword" name="currentPassword"/></div>
<div><label for="newPassword">New Password:</label>
<input type="password" id="newPassword" name="newPassword"/></div>
<div><label for="confirmPassword">Confirm New Password</label>
<input type="password" id="confirmPassword" name="confirmPassword"/></div>
<div><input type="submit" id="submit" name="submit" value="submit"/></div>
</form>
}
@helper Message(string message)
{
<p>@message</p>
}
<style type="text/css">
p,label {color:black;}
</style>
@{
if(!IsPost) {
@RenderForm();
}
else {
var account = Membership.GetUser();
var currentPassword = HttpContext.Current.Request["currentPassword"];
if(Membership.ValidateUser(account.UserName, currentPassword)){
var newPassword = HttpContext.Current.Request["newPassword"];
var confirmPassword = HttpContext.Current.Request["currentPassword"];
if(check(newPassword, confirmPassword)){
account.ChangePassword(account.ResetPassword(), newPassword);
}
}
else {
@Message("The password provided didn't match with the database.");
}
}
}
@functions{
List<string> check(string newPassword, string confirmPassword)
{
//just a place holder
return false;
}
}
我已经尝试在发现错误时添加要填充的List,并且当重新加载表单时,将显示该消息,但RenderForm()函数找不到对List的任何引用。如何显示这些消息?
答案 0 :(得分:1)
您应该使用Web页面框架附带的内置验证。我有一篇文章解释了如何使用它:http://www.mikesdotnetting.com/Article/191/Validation-In-Razor-Web-Pages-2