I am trying to validate some form fields but it always errors out on the Html form helpers. It has something to do with Model binding but I can't get it to work.
What happens below is I get the Form values from the form using the FormsCollection object, then I pass the extracted values to the USerSErvice layer and validate them. When I click on the form it crashes on the Html.Helpers
Thanks!
[In UserController]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(FormCollection formValues)
{
// Get form values
string username = formValues["Username"];
string email = formValues["Email"];
string confirmEmail = formValues["ConfirmEmail"];
string password = formValues["Password"];
string confirmPassword = formValues["ConfirmPassword"];
bool themeRole = Convert.ToBoolean(formValues["ThemeRole"]);
bool valid = _service.CreateUser(username, email, confirmEmail, password, confirmPassword, themeRole);
// If user was created then
if (valid)
{
ViewData["Success"] = true;
}
else
{
ViewData["Success"] = false;
}
return View();
}
[UserService]
region Create User
/// <summary>
/// Create User
/// </summary>
/// <param name="user"></param>
/// <returns></returns>
public bool CreateUser(string username, string email, string confirmEmail, string password, string confirmPassword, bool themeRole)
{
// validate values from form
if (String.IsNullOrEmpty(username) == true)
{
_modelState.AddModelError("Username", "Please provide a username");
}
if (String.IsNullOrEmpty(password) == true)
{
_modelState.AddModelError("Password", "Please provide a password");
}
else if (password.Length < 6)
{
_modelState.AddModelError("Password", "Minimum length for password is 6 characters");
}
if (String.IsNullOrEmpty(confirmPassword) == true)
{
_modelState.AddModelError("ConfirmPassword", "Please confirm your password in the Confirm Password field");
}
else if (!confirmPassword.Equals(password) == true)
{
_modelState.AddModelError("ConfirmPassword", "Passwords do not match");
}
if (String.IsNullOrEmpty(email) == true)
{
_modelState.AddModelError("Email", "Please provide an email address");
}
if (String.IsNullOrEmpty(confirmEmail) == true)
{
_modelState.AddModelError("ConfirmEmail", "Please confirm your email addres in the confirm email field");
}
else if (!confirmEmail.Equals(email) == true)
{
_modelState.AddModelError("ConfirmEmail", "Emails do not match");
}
// if all is good - create account otherwise it fails
if (_modelState.IsValid == true)
{
// Encode password
byt开发者_如何学Goe[] generatedSalt = Utility.GeneratePasswordSalt(new byte[16]);
string saltString = Encoding.Unicode.GetString(generatedSalt);
string passwordSalt = Convert.ToBase64String(generatedSalt);
string newHashedPassword = Utility.EncodePassword(password, passwordSalt);
// Update user object with new user information
User newUser = new User();
newUser.Username = username;
newUser.Password = newHashedPassword;
newUser.PasswordSalt = passwordSalt;
newUser.Email = email;
newUser.Role = themeRole;
// Add user
_repository.AddUser(newUser);
return true;
}
else
{
return false;
}
}
[Error Message]
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 22:
Line 23: Username: Line 24: <%= Html.TextBox("Username") %> Line 25:
Line 26:If you don't want to use built in Model Binding, then to use validation using ModelState.AddModelError you need to the model value as well. In your service layer you will need the following 2 lines for each property.
_modelState.AddModelError("Username", "Please provide a username");
_modelState.SetModelError("Username", ValueProvider["Username"]);
Have a look at these links also:
- Validating form using ModelState
- http://forums.asp.net/p/1396019/3006051.aspx
- ASP.NET MVC - Html.Textbox() throws "Object reference not set to an instance of an object"
精彩评论