Reputation: 97
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);
}
Upvotes: 0
Views: 726
Reputation: 1223
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.
Upvotes: 2