简体   繁体   中英

how to get drop down list selected value

I am new to MVC. So far, I succeeded in binding data from database in a drop down list.

How can I get the selected value and pass it to the Controller to be saved in the database?

Here's what I have done so far:

VIEW:

@Html.DropDownList("State", null, new { @class = "dropdown-toggle col-md-9 form-control" })

CONTOLLER: (this is how bound the data in the dropdown list)

  IEnumerable<SelectListItem> states = db.RefState
            .Select(s => new SelectListItem
            {
                Value = s.ID.ToString(),
                Text = s.Name
            });


        ViewBag.AddressType = types;
        ViewBag.State = states;
        return View();

This is how I save it in the database:

    public ActionResult NewAddress(Address data)
    {
        if(ModelState.IsValid)
        {
            var addressData = new Address()
            {
                ZipCode = data.ZipCode,
                StreetNo = data.StreetNo,
                StreetName = data.StreetName,
                Unit = data.Unit,
                Additional = data.Additional,
                Town = data.Town,
                City = data.City,
                StateID = ?,  
                Description = data.Description,
                VendorCode = data.VendorCode

            };

            db.Address.Add(addressData);
            db.SaveChanges();
            ModelState.Clear();
            data = null;
            ViewBag.Message = "Address succesfully added";
            return RedirectToAction("DeliveryInformation", "DeliveryDetail");
        }

        return View(data);
    }

In your controller method NewAddress add another parameter FormCollection formCollection .

now try:

StateID = formCollection["State"]

Alternatively it might be cleaner to change the name attribute of your dropdownlist to StateID instead of state.

@Html.DropDownList("StateID", null, new { @class = "dropdown-toggle col-md-9 form-control" })

MVC Will only map a control's value to a parameter's property if it's name attribute has exactly the same value as the parameter's property name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM