ASP.NET MVC Model State Validations
<%= Html.ValidationSummary("Account creation was unsuccessful. Please correct the errors and try again.") %>
</div>
<% using (Html.BeginForm("Register", "Account" , FormMethod.Post))
{ %>
<div>
<fieldset>
<legend>Account Information</legend>
<p>
<label for="username">User Name:</label>
<%= Html.TextBox("username") %>
<%= Html.ValidationMessage("username") %>
</p>
<p>
<label for="FirstName">First Name</label>
<%= Html.TextBox("firstName") %>
<%= Html.ValidationMessage("firstName") %>
</p>
<p>
<label for="LastName">Last Name</label>
<%= Html.TextBox("lastName") %>
<%= Html.ValidationMessage("lastName") %>
</p>
<p>
<label for="email">Email:</label>
<%= Html.TextBox("email") %>
<%= Html.ValidationMessage("email") %>
</p>
<p>
<label for="password">Password:</label>
<%= Html.Password("password") %>
<%= Html.ValidationMessage("password") %>
</p>
<p>
<label for="confirmPassword">Confirm password:</label>
<%= Html.Password("confirmPassword") %>
<%= Html.ValidationMessage("confirmPassword") %>
</p>
<p>
<label for="Role">Role:</label>
<%= Html.DropDownList("Role",((SelectList)ViewData["Roles"]),"--Select One---") %>
</p>
<p>
<input type="submit" value="Register" />
</p>
</fieldset>
</div>
<% } %>
private ModelStateDictionary _modelState;
public AccountController() : this(null, null)
{
_modelState = new ModelStateDictionary();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Register(string username, string firstName, string lastName, string password, string confirmPassword, string email, string role)
{
try
{
if (string.IsNullOrEmpty(password))
_modelState.AddModelError("password", "passowrd field is empty");
if (string.IsNullOrEmpty(confirmPassword))
_modelState.AddModelError("confirmPassword", "Confim Passowrd field is empty");
if (string.IsNullOrEmpty(username))
_modelState.AddModelError("username", "UserName field is empty");
if (string.IsNullOrEmpty(email))
_modelState.AddModelError("email", "Email field cannot be empty");
Regex regEmail = new Regex(@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
if (!regEmail.IsMatch(email))
_modelState.AddModelError("email", " The email id submitted is not in valid format");
if (string.IsNullOrEmpty(firstName))
_modelState.AddModelError("firstName", "First name field is empty");
if (string.IsNullOrEmpty(lastName))
_modelState.AddModelError("lastName", "Last name field is empty");
if (!password.Equals(confirmPassword, StringComparison.InvariantCultureIgnoreCase))
_modelState.AddModelError("password", "Password do not match");
if (_modelState.IsValid)
{
int id = _UsrService.GetRoleId(role);
Data.User usr = new User(username, firstName, lastName, email, DateTime.Now, null, id);
string retRegister = _UsrService.RegisterUser(usr, password, confirmPassword, "none", "none");
if (retRegister.Equals("true"))
{
UserRolesControl contrl = new UserRolesControl(Users(), Roles());
return View("Control", contrl);
}
else
{
ModelState.AddModelError("_Form", retRegister);
ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
var roles = _UsrService.GetRoles().ToList();
ViewData["Roles"] 开发者_如何学运维= new SelectList(roles);
return View();
}
}
else
{
var roles = _UsrService.GetRoles().ToList();
ViewData["Roles"] = new SelectList(roles);
return View();
}
}
catch (Exception ex)
{
return View();
}
}
Above is a registrations form, I am working on validations on it. It does run through fine in the controller method , but it does not display the error messages when it send back to register page. It there anything wrong with my code?
What's _modelState
? Why not use ModelState
instead?
Or just Data Annotations for client side validation as well.
In this code, you are not returning the ModelState, that is why no errors are showing. Just use ModelState
instead of _modelState
, and you should be all set.:
if (_modelState.IsValid)
{
//blah
}
else
{
var roles = _UsrService.GetRoles().ToList();
ViewData["Roles"] = new SelectList(roles);
return View();
}
精彩评论