I have successfully populated my drop down list using a dropdownlistfor html helper, however when I submit the form the selected items value is not being passed with the model into the action result. Here is my code sample
Customer Model
public class Customer
{
public int Id { get; set; }
[Required]
[StringLength(255)]
public string Name { get; set; }
[StringLength(11)]
[Display(Name="Date of birth")]
public string BirthDate { get; set; }
public bool IsSubscribedToNewsLetter { get; set; }
public MembershipType MembershipType { get; set; }
[Display(Name = "Membership type")]
public MembershipType MembershipTypeId { get; set; }
}
MembershipType Model
public class MembershipType
{
public int Id { get; set; }
[StringLength(15)]
public string Name { get; set; }
public short SignUpFee { get; set; }
public byte DurationInMonths { get; set; }
public byte DiscountRate { get; set; }
}
Customer View Model
public class NewCustomerViewModel
{
public IEnumerable <MembershipType>MembershipTypes { get; set; }
public Customer Customer { get; set; }
}
View
@model MovieApp.ViewModels.NewCustomerViewModel
@{
ViewBag.Title = "New";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>New Customer</h2>
@using (Html.BeginForm("Create", "Customers"))
{
<div class="form-group">
@Html.LabelFor(c => c.Customer.Name)
@Html.TextBoxFor(c => c.Customer.Name, new { @class = "form-control" })
</div>
<div class="form-group">
@Html.LabelFor(c => c.Customer.BirthDate)
@Html.TextBoxFor(c => c.Customer.BirthDate, new { @class = "form-control" })
</div>
<div class="form-group">
@Html.LabelFor(c => c.Customer.MembershipType)
@Html.DropDownListFor(c => c.Customer.MembershipType
,new SelectList(Model.MembershipTypes, "Id","Name")
,"Select Membership Type"
,new { @class = "form-control" })
</div>
<div class="checkbox">
<label>
@Html.CheckBoxFor(c => c.Customer.IsSubscribedToNewsLetter) Subscribed to newsletter?
</label>
</div>
<button type="submit" class="btn btn-primary">Save</button>
}
Action
public ActionResult New()
{
var DBmebershipTypes= _context.MembershipTypes.ToList();
var ViewModel = new NewCustomerViewModel()
{
MembershipTypes = DBmebershipTypes
};
return View(ViewModel);
}
Post Action
[HttpPost]
public ActionResult Create(Customer customer)
{
_context.Customers.Add(customer);
_context.SaveChanges();
return RedirectToAction("Index", "Customers");
}
When I debug the program, all inputed values are in memory, but the moment it has to be saved to database, dropdownlist selection doesent get saved.