[RESOLVED]How comes i cant get my 3 dropdownlist value?

Hi, i am trying to put 3 dropdownlist DAY , MONTH, YEAR in  stead of a single field : DateOfBirth

I modify my register view page  Account/Register.cshtml  like this :

        <div class="form-group">
            @Html.LabelFor(m => m.DateOfBirth, new { @class = "col-md-4 control-label" })
            <div class="col-md-8">
                @Html.DropDownList("DateOfBirthDay", Enumerable.Range(1, 31).Select(i => new SelectListItem { Value = i.ToString(), Text = i.ToString() }), "-- Select Day --")
                @Html.DropDownList("DateOfBirthMonth", Enumerable.Range(1, 12).Select(i => new SelectListItem { Value = i.ToString(), Text = System.Globalization.CultureInfo.InvariantCulture.DateTimeFormat.GetMonthName(i) }), "-- Select Month --")
                @Html.DropDownList("DateOfBirthYear", Enumerable.Range(1900, 109).Select(i => new SelectListItem { Value = i.ToString(), Text = i.ToString() }), "-- Select Year --")
                @Html.ValidationMessageFor(m => m.DateOfBirth)
            </div>
        </div>

I updated my controller with the following :

 //
        // POST: /Account/Register
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Register([Bind(Include = "DateOfBirthDay,DateOfBirthMonth,DateOfBirthYear")] RegisterViewModel model)

this is my  RegisterViewModel : (AccountViewModels.cs)

 public class RegisterViewModel
    {
        [Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(ViewRes.ValidationStrings))]
        [DataType(DataType.EmailAddress)]
        [RegularExpression(@"^([a-zA-Z0-9_-.]+)@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.)|(([a-zA-Z0-9-]+.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(]?)$", ErrorMessageResourceName = "Invalid", ErrorMessageResourceType = typeof(ViewRes.ValidationStrings))]
        [Display(Name = "UserName", ResourceType = typeof(ViewRes.Names))]
        public string UserName { get; set; }

        [Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(ViewRes.ValidationStrings))]
        [StringLength(100, ErrorMessageResourceName = "PasswordMinLength", ErrorMessageResourceType = typeof(ViewRes.ValidationStrings), MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "Password", ResourceType = typeof(ViewRes.Names))]
        public string Password { get; set; }

        [DataType(DataType.Password)]
        [Display(Name = "ConfirmPassword", ResourceType = typeof(ViewRes.Names))]
        [Compare("Password", ErrorMessageResourceName = "PasswordMustMatch", ErrorMessageResourceType = typeof(ViewRes.ValidationStrings))]
        public string ConfirmPassword { get; set; }

        // New Fields added to extend Application User class:
        [Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(ViewRes.ValidationStrings))]
        [Display(Name = "FirstName", ResourceType = typeof(ViewRes.Names))]
        public string FirstName { get; set; }

        [Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(ViewRes.ValidationStrings))]
        [Display(Name = "LastName", ResourceType = typeof(ViewRes.Names))]
        public string LastName { get; set; }

        [Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(ViewRes.ValidationStrings))]
        [Display(Name = "Sex", ResourceType = typeof(ViewRes.Names))]
        public string Sex { get; set; }

        [Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(ViewRes.ValidationStrings))]
        [Display(Name = "DateofBirth", ResourceType = typeof(ViewRes.Names))]
        [DataType(DataType.DateTime)]
        [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
        public DateTime DateOfBirth { get; set; }

        public DateTime DateOfRegistration { get; set; }

        public bool UserNewsletter { get; set; }

        public string DefaultLanguage { get; set; }

        public string RealUserLanguage { get; set; }
        
        // Return a pre-poulated instance of AppliationUser:
        public ApplicationUser GetUser()
        {
            //Generate random code
            string randomcode = "";
            Random random = new Random();
            int length = 8;
            for (int i = 0; i < length; i++)
            {
                if (random.Next(0, 3) == 0)                     //if random.Next() == 0 then we generate a random character
                {
                    randomcode += ((char)random.Next(65, 91)).ToString();
                }
                else                                            //if random.Next() == 0 then we generate a random digit
                {
                    randomcode += random.Next(0, 9);
                }
            }



            //Get the language of the user
            string defaultlanguage = "en";
            string langName = "en";
            if (HttpContext.Current.Request.UserLanguages != null && HttpContext.Current.Request.UserLanguages.Length != 0)
            {

                defaultlanguage = HttpContext.Current.Request.UserLanguages[0].Substring(0, 2);

                if (defaultlanguage == "it")
                {
                    langName = "it";
                }
                if (defaultlanguage == "fr")
                {
                    langName = "fr";
                }
                if (defaultlanguage == "es")
                {
                    langName = "es";
                }

            }



            var user = new ApplicationUser()
            {

                UserName = this.UserName,

                FirstName = this.FirstName,

                LastName = this.LastName,

                Sex = this.Sex,

                DateOfBirth = this.DateOfBirth,

                DateOfRegistration = DateTime.Now,

                PasswordNotHashed = this.ConfirmPassword,

                CodeVerification = randomcode,

                UserActive = true,

                UserNewsletter = this.UserNewsletter,

                DefaultLanguage = langName,

                RealUserLanguage = defaultlanguage,

            };
            return user;
        }
    }

But when i try to get the 3 dropdownlist data in my controller it looks like they don’t exist… why?

example

 DateOfBirthYear = model.DateOfBirthYear;

Thanks

Hi,

Either you can go for Strongly Typed DropdownListFor or if you want to stick for the same code then you can pass the parameters in your post method like below -

YourPostMethod(string DateOfBirthDay , string DatehOfBirthMonth, string DateOfBirthYear)

{



}

Hi, like this i can see them, but how can i make them as a required fields?

because, when i register,  if i don’t choose any day or month or year i get error :

Erreur du serveur dans l'application '/'.

La chaîne n'a pas été reconnue en tant que DateTime valide.

Description : Une exception non gérée s'est produite au moment de l'exécution de la requête Web actuelle. Contrôlez la trace de la pile pour plus d'informations sur l'erreur et son origine dans le code. 

Détails de l'exception: System.FormatException: La chaîne n'a pas été reconnue en tant que DateTime valide.

Erreur source: 


Ligne 820 :                {
Ligne 821 :                    // do for invalid date
Ligne 822 :                    DateTime FullDateOfBirthLastFormatDate = Convert.ToDateTime(FullDateOfBirthLast);
Ligne 823 :                    user.DateOfBirth = FullDateOfBirthLastFormatDate;
Ligne 824 :

you should add the three down drown fields to the view model and make them required.

Leave a Reply