Home > other >  Populate DropDownList if CheckBox not checked
Populate DropDownList if CheckBox not checked

Time:04-12

Having trouble populating my DropDownList if user attempts to submit form without selecting the CheckBox.

If user fills out all required fields and does not select the checkbox and then clicks on submit the values in the DropDownList are removed. I'm not sure were or how to populate those values again if the user does not initially select the CheckBox.

RenterViewModel below:

public class RenterViewModel
{
    [Required(ErrorMessage = "First Name is required")]
    [Display(Name = "First Name")]
    [StringLength(25)]
    [MaxLength(25)]
    public string RenterFirstName { get; set; }

    [Required(ErrorMessage = "Last Name is required")]
    [Display(Name = "Last Name")]
    [StringLength(25)]
    [MaxLength(25)]
    public string RenterLastName { get; set; }

    [Required(ErrorMessage = "Address is required")]
    [Display(Name = "Address")]
    [StringLength(50)]
    [MaxLength(50)]
    public string RenterAddress { get; set; }

    [Required(ErrorMessage = "City is required")]
    [Display(Name = "City")]
    [StringLength(35)]
    [MaxLength(35)]
    public string RenterCity { get; set; }

    [Required(ErrorMessage = "Zip Code is required")]
    [Display(Name = "Zip Code")]
    [StringLength(5, MinimumLength = 5, ErrorMessage = "Zip Code should have minimum 5 digits")]
    [MaxLength(5)]
    [RegularExpression("([1-9][0-9]*)", ErrorMessage = "Numeric values only")]
    public string RenterZipCode { get; set; }

    [Required(ErrorMessage = "Phone Number is required")]
    [Display(Name = "Phone Number")]
    [DataType(DataType.PhoneNumber)]
    [RegularExpression(@"^(\ 0?1\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$", ErrorMessage = "Not a valid Phone number")]
    public string RenterPhoneNumber { get; set; }

    [Required(ErrorMessage = "Email Address is required")]
    [Display(Name = "Email Address")]
    [DataType(DataType.EmailAddress)]
    [MaxLength(255)]
    [RegularExpression(@"[a-z0-9._% -] @[a-z0-9.-] \.[a-z]{2,4}", ErrorMessage = "Incorrect Email Format")]
    public string RenterEmailAddress { get; set; }

    [Required(ErrorMessage = "Date of Birth is required")]
    [Display(Name = "Date of Birth")]
    [DataType(DataType.Date)]
    public DateTime RenterDateOfBirth { get; set; }

    [Required(ErrorMessage = "Name of Employer is required")]
    [Display(Name = "Name of Employer")]
    [StringLength(50)]
    [MaxLength(50)]
    public string RenterEmployerName { get; set; }

    [Required(ErrorMessage = "Employer Phone Number is required")]
    [Display(Name = "Employer Phone Number")]
    [DataType(DataType.PhoneNumber)]
    [RegularExpression(@"^(\ 0?1\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$", ErrorMessage = "Not a valid Phone number")]
    public string RenterEmployerPhoneNumber { get; set; }

    [Required(ErrorMessage = "Length of Employment is required")]
    [Display(Name = "Length of Employment")]
    [MaxLength(50)]
    public string RenterEmploymentLength { get; set; }

    [Required(ErrorMessage = "Monthly Gross Income is required")]
    [Display(Name = "Monthly Gross Income")]
    [Range(1, 100000000), DataType(DataType.Currency)]
    public decimal RenterEmploymentGrossIncome { get; set; }

    [Required(ErrorMessage = "Total number of persons to occupy apartment is required")]
    [Display(Name = "Total number of persons to occupy apartment")]
    [Range(1, 10, ErrorMessage = "Must be between 1 to 10")]
    public int RenterTotalPersonsOccupy { get; set; }

    [Required(ErrorMessage = "Total number of children to occupy apartment is required")]
    [Display(Name = "Total number of Children to occupy apartment")]
    [Range(0, 10, ErrorMessage = "Must be between 0 to 10")]
    public int RenterTotalChildrenOccupy { get; set; }

    //[Required(ErrorMessage = "You must exept terms to continue")]
    [Display(Name = "I agree to the Terms")]
    [Range(typeof(bool), "true", "true", ErrorMessage = "You must accept the Terms")]
    //[Controllers.RenterController.CheckBoxRequired(ErrorMessage = "Please checked the items")]
    public bool RenterAllowTerms { get; set; }

    [Required(ErrorMessage = "Please select State")]
    [Display(Name = "State")]
    public int StateId { get; set; }
    public IEnumerable<SelectListItem> States { get; set; }
} code here

RenterController below:

public class RenterController : Controller
{
    private readonly ApplicationDbContext _db;
    public RenterController(ApplicationDbContext db)
    {
        _db = db;
    }

    // GET: /Renters List/
    public IActionResult Index()
    {
        IEnumerable<Renter> objList = _db.Renters;
        return View(objList);
    }

    // GET: /Create
    public IActionResult Create()
    {
        RenterViewModel rentervm = new RenterViewModel()
        {
            States = _db.States.Select(i => new SelectListItem
            {
                Text = i.StateInitial,
                Value = i.StateId.ToString()
            })
        };

        return View(rentervm);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create(RenterViewModel rentervm)
    {
        if (ModelState.IsValid)
        {
            var renterobj = new Renter();
            {
                renterobj.RenterFirstName = rentervm.RenterFirstName;
                renterobj.RenterLastName = rentervm.RenterLastName;
                renterobj.RenterAddress = rentervm.RenterAddress;
                renterobj.RenterCity = rentervm.RenterCity;
                renterobj.StateId = rentervm.StateId;
                renterobj.RenterZipCode = rentervm.RenterZipCode;
                renterobj.RenterPhoneNumber = rentervm.RenterPhoneNumber;
                renterobj.RenterEmailAddress = rentervm.RenterEmailAddress;
                renterobj.RenterDateOfBirth = rentervm.RenterDateOfBirth;
                renterobj.RenterEmployerName = rentervm.RenterEmployerName;
                renterobj.RenterEmployerPhoneNumber = rentervm.RenterEmployerPhoneNumber;
                renterobj.RenterEmploymentLength = rentervm.RenterEmploymentLength;
                renterobj.RenterEmploymentGrossIncome = rentervm.RenterEmploymentGrossIncome;
                renterobj.RenterTotalPersonsOccupy = rentervm.RenterTotalPersonsOccupy;
                renterobj.RenterTotalChildrenOccupy = rentervm.RenterTotalChildrenOccupy;
                renterobj.RenterAllowTerms = rentervm.RenterAllowTerms;
            }

            _db.Renters.Add(renterobj);
            await _db.SaveChangesAsync();
            return RedirectToAction("Index");
        }

        return View(rentervm);
    }

Create View:

<form method="post" asp-action="Create">
<div >
    <div >
        <h2 >Preliminary Rental Application</h2>
    </div>
    <div >
        <div >
            <div >
                <div >
                    <label asp-for="RenterFirstName"></label>
                    <input asp-for="RenterFirstName"  />
                    <span asp-validation-for="RenterFirstName" ></span>
                </div>
                <div >
                    <label asp-for="RenterLastName"></label>
                    <input asp-for="RenterLastName"  />
                    <span asp-validation-for="RenterLastName" ></span>
                </div>
                <div >
                    <label asp-for="RenterAddress"></label>
                    <input asp-for="RenterAddress"  />
                    <span asp-validation-for="RenterAddress" ></span>
                </div>
                <div >
                    <label asp-for="RenterCity"></label>
                    <input asp-for="RenterCity"  />
                    <span asp-validation-for="RenterCity" ></span>
                </div>

                <div >
                    <label asp-for="StateId"></label>
                    <select asp-for="StateId" asp-items="@Model.States" >
                        <option></option>
                    </select>
                    <span asp-validation-for="StateId" ></span>
                </div>

                <div >
                    <label asp-for="RenterZipCode"></label>
                    <input asp-for="RenterZipCode"  />
                    <span asp-validation-for="RenterZipCode" ></span>
                </div>
                <div >
                    <label asp-for="RenterPhoneNumber"></label>
                    <input asp-for="RenterPhoneNumber" type="tel"  />
                    <span asp-validation-for="RenterPhoneNumber" ></span>
                </div>
                <div >
                    <label asp-for="RenterEmailAddress"></label>
                    <input asp-for="RenterEmailAddress" type="email"  />
                    <span asp-validation-for="RenterEmailAddress" ></span>
                </div>
                <div >
                    <label asp-for="RenterDateOfBirth"></label>
                    <input asp-for="RenterDateOfBirth" type="date"  />
                    <span asp-validation-for="RenterDateOfBirth" ></span>
                </div>
                <div >
                    <label asp-for="RenterEmployerName"></label>
                    <input asp-for="RenterEmployerName"  />
                    <span asp-validation-for="RenterEmployerName" ></span>
                </div>
                <div >
                    <label asp-for="RenterEmployerPhoneNumber"></label>
                    <input asp-for="RenterEmployerPhoneNumber" type="tel"  />
                    <span asp-validation-for="RenterEmployerPhoneNumber" ></span>
                </div>
                <div >
                    <label asp-for="RenterEmploymentLength"></label>
                    <input asp-for="RenterEmploymentLength" type="tel"  />
                    <span asp-validation-for="RenterEmploymentLength" ></span>
                </div>
                <div >
                    <label asp-for="RenterEmploymentGrossIncome"></label>
                    <input asp-for="RenterEmploymentGrossIncome"  />
                    <span asp-validation-for="RenterEmploymentGrossIncome" ></span>
                </div>
                <div >
                    <label asp-for="RenterTotalPersonsOccupy"></label>
                    <input asp-for="RenterTotalPersonsOccupy"  />
                    <span asp-validation-for="RenterTotalPersonsOccupy" ></span>
                </div>
                <div >
                    <label asp-for="RenterTotalChildrenOccupy"></label>
                    <input asp-for="RenterTotalChildrenOccupy"  />
                    <span asp-validation-for="RenterTotalChildrenOccupy" ></span>
                </div>
                <div >
                    <label asp-for="RenterAllowTerms"></label>
                    <input asp-for="RenterAllowTerms">
                    <span asp-validation-for="RenterAllowTerms" ></span>
                </div>
            </div>

            <div >
                <div >
                    <div >
                        <input type="submit"  value="create" />
                    </div>
                    <div >
                        <a asp-action="Index" >Back</a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

CodePudding user response:

Assuming your ModelState.IsValid is returning false (since you are requiring the user to check the checkbox before submitting) and for some reason you are losing the data in your States field, you should re-populate the States select list item, before you return your view.

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(RenterViewModel rentervm)
    {
        if (ModelState.IsValid)
        {
            var renterobj = new Renter();
            {
                renterobj.RenterFirstName = rentervm.RenterFirstName;
                renterobj.RenterLastName = rentervm.RenterLastName;
                renterobj.RenterAddress = rentervm.RenterAddress;
                renterobj.RenterCity = rentervm.RenterCity;
                renterobj.StateId = rentervm.StateId;
                renterobj.RenterZipCode = rentervm.RenterZipCode;
                renterobj.RenterPhoneNumber = rentervm.RenterPhoneNumber;
                renterobj.RenterEmailAddress = rentervm.RenterEmailAddress;
                renterobj.RenterDateOfBirth = rentervm.RenterDateOfBirth;
                renterobj.RenterEmployerName = rentervm.RenterEmployerName;
                renterobj.RenterEmployerPhoneNumber = rentervm.RenterEmployerPhoneNumber;
                renterobj.RenterEmploymentLength = rentervm.RenterEmploymentLength;
                renterobj.RenterEmploymentGrossIncome = rentervm.RenterEmploymentGrossIncome;
                renterobj.RenterTotalPersonsOccupy = rentervm.RenterTotalPersonsOccupy;
                renterobj.RenterTotalChildrenOccupy = rentervm.RenterTotalChildrenOccupy;
                renterobj.RenterAllowTerms = rentervm.RenterAllowTerms;
            }

            _db.Renters.Add(renterobj);
            await _db.SaveChangesAsync();
            return RedirectToAction("Index");
        }

        //you should re populate the States field here before returning the view
        return View(rentervm);
    }
  • Related