Question

 var vatRate = new List<SelectListItem>();
            vatRate.Add(new SelectListItem { Text = "Please select...", Value = "0", Selected = false });
            vatRate.Add(new SelectListItem { Text = "0%", Value = "0", Selected = false });
            vatRate.Add(new SelectListItem { Text = "5%", Value = "5", Selected = false });
            vatRate.Add(new SelectListItem { Text = "20%", Value = "20", Selected = false });
            model.VatRate = vatRate;

This is the code that initialises a list that will populate my dopdownlist in my view. On my model part is as

[Required]
        [Display(Name = "VAT Rate")]
        public IEnumerable<SelectListItem> VatRate { get; set; }
        public IEnumerable<SelectListItem> selectedVatRate { get; set; }

and in my view I did like

 @Html.DropDownListFor(m => m.selectedVatRate, Model.VatRate, new { @class = "form-control" })

however when this page is posted I am getting selectedVatRate's count = 0

Why so ?

and Is there a way only to accept the VALUE from the dropdownlist itself ?

Was it helpful?

Solution

This is how it works. What you have on POST action is what parameters were posted on the form. For instance the drop down will post a single number (or string) representing selected value (0, 5, 20). So basically instead of

public IEnumerable<SelectListItem> selectedVatRate { get; set; }

you need

public int selectedVatRate { get; set; }

for this to be handled correctly. Then on post selectedVatRate will contain the selected value as an integer (for example 5 in user selected 5% option).

Side note. You have the same value for default list item and for the first option of 0%. This does not look right, as you won't be able to tell one from the other on post. So you might want default value to be empty:

Text = "Please select...", Value = ""

and turn the selectedVatRate field to int?. Then on post you will get null if default option is selected, and 0 in case of 0%.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top