Reputation: 5908
I have a dropdownlistFor that is not posting the selected value from the dropdown list back to the server.
This is the ViewModel
public class DonationViewModel
{
public int Id { get; set; }
public int AttendeeId { get; set; }
public int EventId { get; set; }
public string EventName { get; set; }
[Display(Name = "Address Line 1")]
[RequiredIfTrue("GiftAid")]
public string Address1 { get; set; }
[Display(Name = "Address Line 2")]
public string Address2 { get; set; }
[Display(Name = "City/Town")]
[RequiredIfTrue("GiftAid")]
public string City { get; set; }
[Display(Name = "Post Code")]
[RequiredIfTrue("GiftAid")]
public string PostCode { get; set; }
[Display(Name = "Gift Aid")]
public bool GiftAid { get; set; }
public decimal Amount { get; set; }
[Display(Name = "Donation Paid?")]
public bool Paid { get; set; }
[Display(Name = "Payment Method")]
public PaymentMethod? PaymentMethod { get; set; }
[Display(Name = "Date Donation Paid")]
public DateTime? DatePaid { get; set; }
public IEnumerable<SelectListItem> Attendees { get; set; }
}
Here is the controller action That sets the model up
public virtual ActionResult Donate(int eventId)
{
var model = new DonationViewModel()
{
EventId = eventId,
EventName = _eventService.GetById(eventId).Name,
Attendees = _attendeeService.GetByEvent(eventId).Select(x=> new SelectListItem
{
Value = x.Id.ToString(),
Text = string.Format("{0} {1} ({2})", x.FirstName, x.LastName, x.Email)
})
};
return View(model);
}
This is the view Code
<div class="form-group">
@Html.LabelFor(model => model.Attendees, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.AttendeeId, new SelectList(Model.Attendees, "Value", "Text"), "Please Select an Attendee")
@Html.ValidationMessageFor(model => model.Address1)
</div>
</div>
AttendeeId
is always 0 when posted back instead of the selected value
Upvotes: 2
Views: 1872
Reputation: 5908
I'm almost embarrassed to say that on the page there was a Hidden Field for AttendeeId, which was being assigned the correct value. This meant that there were two values for AttendeeId being posted back to the server, but the Model binder used the second, Empty value to bind to the view model.
So the takeaway for me, is always inspect the POST as well as what's being bound to the model....
Upvotes: 3
Reputation: 3787
Try
@Html.DropDownListFor(model => model.AttendeeId, new SelectList(Model.Attendees, "Text", "Value", Model.AttendeeId ))
Upvotes: 0
Reputation: 13640
You don't need to wrap it with a SelectList
, DropDownListFor method takes an IEnumerable<SelectListItem>
as a parameter and you already have it:
@Html.DropDownListFor(model => model.AttendeeId, Model.Attendees, "Please Select an Attendee")
Upvotes: 1