DropDownList选择的值未发布到服务器ASP.NET MVC

时间:2014-02-20 06:37:46

标签: asp.net-mvc

我有一个dropdownlist,因为它没有将下拉列表中的选定值发布回服务器。

这是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; } 
}

以下是设置模型的控制器操作

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);
    }

这是视图代码

<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始终为0,而​​不是选定的值

3 个答案:

答案 0 :(得分:3)

我几乎不好意思地说,在页面上有一个隐藏字段用于AttendeeId,它被分配了正确的值。这意味着AttendeeId有两个值被发布回服务器,但Model绑定器使用第二个Empty值绑定到视图模型。

所以对我来说,总是检查POST以及绑定到模型的内容....

答案 1 :(得分:1)

您不需要使用SelectList包裹它,DropDownListFor方法需要IEnumerable<SelectListItem>作为参数,您已经拥有它:

@Html.DropDownListFor(model => model.AttendeeId, Model.Attendees, "Please Select an Attendee")

答案 2 :(得分:0)

尝试

@Html.DropDownListFor(model => model.AttendeeId, new SelectList(Model.Attendees, "Text", "Value", Model.AttendeeId ))