Ilhan
Ilhan

Reputation: 1331

Dropdownfor selected item changes after ModelState is invalid

When I send my view model with POST to my controller (with no city selected) I get an expected "required city" error but when I select a city (say first in list) and then I have another error (for example first name is missing) so my model state is still not valid it redirects me to the initial page and selects suddenly some city from the bottom (or random at times)

In the view

 @Html.DropDownListFor(m => m.CityID, Model.SelectListCities, "Select City", new { @class = "form-control", @name = "City" })

In the controller

 public ActionResult Registration()
    {
        RegisteredVisitorVM Model = new RegisteredVisitorVM();

        List<City> cities = principal.Cities.ToList().OrderBy(x => x.Name).ToList();
        List<SelectListItem> cityList = new List<SelectListItem>();

        cityList.AddRange(cities.Select(
                x => new SelectListItem { Value = x.CountryID.ToString(), Text = x.Name }
            ).ToList()
        );

        Model.SelectListCities = cityList;
        return View("RegistrationView", Model);
    }
    public ActionResult SubmitRegisteredVisitors(RegisteredVisitorVM model)
    {
        if (!ModelState.IsValid)
        {
            List<SelectListItem> cityList = new List<SelectListItem>();
            List<City> cities = principal.Cities.ToList().OrderBy(x => x.Name).ToList();

            cityList.AddRange(cities.Select(
                    x => new SelectListItem { Value = x.CountryID.ToString(), Text = x.Name }
                ).ToList()
            );

            model.SelectListCities = cityList;
            return View("RegistrationView", model);
        }

        return Content(model.FirstName);
    }

In the ViewModel

using CondorExtreme3.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace CondorExtreme3.Areas.Users.Models
{
    public class RegisteredVisitorVM
    {
    [MaxLength(50, ErrorMessage = "First name is too long!")]
    [Required(ErrorMessage = "First name is required!")]
    public string FirstName { get; set; }

    [MaxLength(50, ErrorMessage = "Last name is too long!")]
    [Required(ErrorMessage = "Last name is required!")]
    public string LastName { get; set; }

    [Index(IsUnique = true)]
    [MaxLength(30, ErrorMessage = "Username is too long!")]
    [Required(ErrorMessage = "Username is required!")]
    public string UserName { get; set; }

    [MaxLength(30, ErrorMessage = "Password is too long!")]
    [MinLength(8, ErrorMessage = "Must have at least 8 characters!")]
    [RegularExpression("^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{2,}$", ErrorMessage = "Must be alpha-numeric!")]
    [Required(ErrorMessage = "Password is required!")]
    public string Password { get; set; }

    [Required(ErrorMessage = "Phone number is required!")]
    public string PhoneNumber { get; set; }

    [Index(IsUnique = true)]
    [Required(ErrorMessage = "Email is required!")]
    [RegularExpression("^[^@]+@[^@]+\\.[^@]+$", ErrorMessage = "Invalid format!")]
    public string Email { get; set; }

    [Required(ErrorMessage = "City is required!")]
    public int CityID{ get; set; }
    public List<SelectListItem> SelectListCities { get; set; }
}

}

Upvotes: 1

Views: 63

Answers (1)

Kadaj
Kadaj

Reputation: 695

Hej Ilhan, I had this exact problem when I was creating some seminar work for college.

First time I wasn't re-populating list when validation fails, and second time is when inteli sense was creating issue, which I resolved only after restarting VS. So in short, if you are using Code First are you sure that var name is "CountryID" and not "CountryId"? :D

Upvotes: 1

Related Questions