Search code examples
c#asp.net-mvcrazorhtml.dropdownlistforformcollection

Post Dropdown values/keys using FormCollection


I have a form that posts to an action:

 public ActionResult Index()
    {
        CheckDataVM vm = new CheckDataVM();
        vm.SerialNumbers = GetAllSerials();
        vm.CustomerNames = GetAllCustomers();
        vm.DateFrom = DateTime.Now.AddDays(-1);
        vm.DateTo = DateTime.Now;

        return View(vm);
    }       

    [HttpPost]
    public ActionResult Index(CheckDataVM v)
    {
        CheckDataVM vm = new CheckDataVM();
        vm.SerialNumbers = GetAllSerials();
        var s = vm.SerialNumbers.First().Text.ToString();
        vm.Channels = GetAllChannels(s);

        vm.DateFrom = DateTime.Now.AddDays(-1);
        vm.DateTo = DateTime.Now;

        return View(vm);
    }

In my Razor view, I have post:

@using (Html.BeginForm("Index", "CheckData", FormMethod.Post, new { id = "SerialsForm" }))
{
    <div class="card-body" style="font-size: small;">
        <div class="form-group">
            @Html.DropDownListFor(x => x.SelectedSerial, Model.SerialNumbers, new { @class = "form-control form-control-sm" })
            <input type="submit" value="Submit" />
        </div>
    </div>
} 

The view model is:

 public class CheckDataVM
    {         
        public string CustomersName { get; set; }
        public string SelectedSerial { get;set; }

        [Display(Name="Select a serial number")]
        public IEnumerable<SelectListItem> SerialNumbers { get; set; }
    }  

The dropdowns work, but when I submit the form the only thing I get back is the object name (SerialNumbers) as the key.

I want to be able to get the selected item from the dropdown list and pass this to the FormCollection in the Httpost of the Index action. For the life of me, I cannot get it to work!

I am expecting to see a key called 'CustomersDdl' and it's value. For example, if I had a dropdown full of countries and I pick England, I am expecting to see a value come back in the FormCollection saying England.

What am I doing wrong?


Solution

  • The value to postback is depending on how you create "SelectListItem", in your case it is in the method "GetAllSerials()"

      vm.SerialNumbers = serialNumbers.Select(serial => new SelectListItem
            {
                Selected = serial.id == vm.SelectedSerial ? true : false,
                Text = serial.Name,
                Value = serial.Name
            }).ToList();