Razor - 通过Ajax.BeginForm将DropDownList选择的值传递给Controller

时间:2013-11-03 19:58:52

标签: ajax asp.net-mvc-4 razor html-select

我正在尝试将dropdownlist值传递给我的控制器,以便我可以将值添加到付费代码列表中,但我不断得到“值不能为空”。错误。我的付费清单中有很多项目。不确定这里有什么是空或错...

INNER EXCEPTION

Value cannot be null.
Parameter name: source

查看

        <!-- products input-->
        <div class="control-group col-lg-6">
            <label class="control-label">Product</label>
            <div class="controls">
                @using (Ajax.BeginForm("AddPayCode", "Referral",
    new AjaxOptions()
    {
        HttpMethod = "POST",
        InsertionMode = InsertionMode.Replace,
        UpdateTargetId = "PayCodes",
        Url = Url.Action("AddPayCode", "Referral")
    }))
                {
                    @Html.ValidationSummary()

                    @Html.DropDownListFor(model => model.SelectedPayCode, new SelectList(Model.PayCodes.ToList(), "Id", "Description"), "- Select -")
                    <input type="submit" value="Add" />
                }
            </div>
        </div>

CONTROLLER

[HttpPost]
public void AddPayCode(ReferralModel model)
{
    var test = model.SelectedPayCode;
    //TODO: Add to model.Referral.PayCodes list and return list of selected items
}

MODEL

public class ReferralModel
{
    public Customer Customer { get; set; }
    public Employee Employee { get; set; }
    public List<PayCode> PayCodes { get; set; }
    public int SelectedPayCode { get; set; }

    public Referral Referral { get; set; }
}

DOMAIN OBJECT

public class Referral
{
    [Key]
    public int Id { get; set; }
    public int CustomerId { get; set; }
    public int EmployeeId { get; set; }
    public decimal Total { get; set; }

    public virtual List<PayCode> PayCodes { get; set; }
    public virtual Customer Customer { get; set; }
    public virtual Employee Employee { get; set; }
}

目标:

  • 用户从下拉列表中选择付费代码并点击“添加”付款代码

  • 添加到推介PayCodes列表

  • Controller返回所选择的付费代码列表(不是 尚未实施)

1 个答案:

答案 0 :(得分:1)

问题是控制器缺少下拉列表的属性。

[HttpPost]
public void AddPayCode(ReferralModel model, ** string SelectedPayCode ** <-- missing)
{
    var test = SelectedPayCode;
    //TODO: Add to model.Referral.PayCodes list and return list of selected items
}