modelstate validation in asp.net mvc 2.0

I have implemented customised registratio page by extending the membership provider using profile provider.I successfully registered the user .Now i want to validate the fields of registration page.Built-in Registration page has builtin validation messages. Bu in my coding i am not passing model to the registration action, instead i am passing properties.So if i Use If(ModelState.IsValid) it is always gives true even i am not filling any fields .but after it throws an exception but not displaying error messages in the page.Please tell me what i have to do.How i am getting my validation messages.

I saw Account Models class in that for register Model built in validation conditions are there.So i am also writing like that for my properties.

Thanks in advance,

public ActionResult UserRegistration(string FirstName, string LastName, string LoginId, string EmailId, string Password, string ConfirmPassword) {

        //int id= int.Parse(ViewData["id"] as string);


            string firstName = FirstName;
            string lastName = LastName;
            string userName = LoginId;
            string email = EmailId;
            string password = Password;
            string confirmPassword = ConfirmPassword;
            if (ModelState.IsValid)
            {
            MembershipCreateStatus status = MembershipService.CreateUser(userName, password, email);
            //MembershipCreateStatus user = Membership.CreateUser(userName, password, email);
            Roles.AddUserToRole(userName, "User");
            UserProfile.NewUser.Initialize(userName, true);
            UserProfile.NewUser.FirstName = firstName;
            UserProfile.NewUser.LastName = lastName;
            if (status == MembershipCreateStatus.Success)
            {
                UserProfile.NewUser.Save();

                FormsService.SignIn(userName, false /* createPersistentCookie */);
                return RedirectToAction("CreateAccountConfirmation");
            }
            else
            {
                ModelState.AddModelError("", AccountValidation.ErrorCodeToString(status));
            }

the ModelState is valid because it's not invalid to have a blank field.

You either have to check every field manually in your action ( if (FirstName == null) ModelState.AddModelError("blabla"); )

or (and that I would suggest) you create a ViewModel and provide it with validation attributes

public class RegistrationModel
{
        [Required]
        public string FirstName { get; set; }
        [Required]
        public string LastName { get; set; }
        [Required]
        public string LoginId { get; set; }
        [Required]
        public string EmailId { get; set; }
        [Required]
        public string Password { get; set; }
        [Required]
        public string ConfirmPassword { get; set; }
}
链接地址: http://www.djcxy.com/p/9696.html

上一篇: .net mvc 2验证:总结几个属性的值

下一篇: 在asp.net mvc 2.0中进行模型状态验证