下拉值获取空值

时间:2016-02-13 19:22:51

标签: c# .net asp.net-mvc dropdown

我将客户端的ClientsName作为dropdownList中的Payments表,所以当我创建付款时,我会按下这样的下拉列表: enter image description here

所以我在我的控制器上安装了一个断点调试,并且Value ClientsName总是为空,但在我的视图中,它始终将我的下拉列表的第一个值放入

enter image description here

型号:

public class Payments
{
    [Key]
    public int PaymentsId { get; set; }

    public int ClientsId { get; set; }
    [ForeignKey("ClientsId")]
    public virtual Clients Clients { get; set; }
    public String Paymentnumber { get; set; }
    public DateTime PaymentDate { get; set; }
    public Decimal Amount { get; set; }
    public Decimal Discount { get; set; }
    public String Reference { get; set; }
    public String Bank { get; set; }
    public Decimal Total { get; set; }

}

获取控制器:

//GET CREATE CONTROLLER

 public ActionResult Create(Payments model)
    {
        var clientList = new PaymentsViewModel
        {
            Clients = new SelectList(db.ClientsList, "ClientsId", "ClientsName")
        };
        return View(clientList);

    }

POST控制器(扩展方法):

 public static PaymentsViewModel PaymentsCreate(this PaymentsViewModel model)
    {
        var paynew = new Payments
        {
            Paymentnumber = model.Paymentnumber,
            PaymentDate = DateTime.Now.Date,
            Amount = model.Amount,
            Discount = model.Discount,
            Reference = model.Reference,
            Bank = model.Bank,
            Total = model.Amount - model.Discount
        };

        db.PaymentsList.Add(paynew);
        db.SaveChanges();
        return model;

    }
}

创建视图:

   @Html.DropDownListFor(x => x.Clients, Model.Clients, new { @class = "form-control", @required = "required" })

我真的不知道这里发生了什么

1 个答案:

答案 0 :(得分:0)

修改您的控制器并指定所选的clientID。

 public ActionResult Create(Payments model)
 {
    ViewBag.Clients = new SelectList(db.ClientsList, "ClientsId", "ClientsName", model.clientID)
    return View();
}

修改你的观点。

 @Html.DropDownListFor(x => x.Clients, ViewBag.Clients, new { @class = "form-control", @required = "required" })