下拉值获取空值

Dropdown value gets null value

我使用断点调试它,我的 ClientsId 总是为空,并且在我的支付索引上显示的总是我的下拉列表的第一个值

型号:

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

    public int ClientId { get; set; }
    public virtual Client Client { get; set; }

}

视图模型:

public class PaymentsViewModel
{
    [Required(ErrorMessage = "Please select a client")]
    [Display(Name = "Client")]
    public int SelectedClient { get; set; }
    public IEnumerable<SelectListItem> Client { get; set; }
}

获取控制器:

  public ActionResult Create(Payments model)
  {
      var liste= new PaymentsViewModel
      {
          Clients = new SelectList(db.ClientList, "ClientId", "ClientName")
      };
      return View(liste);
  }

POST 控制器:

public ActionResult Create([Bind(Include = "....")] PaymentsViewModel model)
{
    if (ModelState.IsValid)
    {
        model.PaymentsCreate();
        return RedirectToAction("Index", "Payments");
    }

    return View(model);
}

创建视图:

            @Html.DropDownListFor(m => m.SelectedClient, Model.Clients, "-Please select-", new { @class = "form-control" })

        </div>
    </div>

----------------------------------------更新---------------------------------------------- -

编辑控制器(获取):

 public ActionResult Edit(int? id, PaymentsViewModel model)
 {
      if (id == null)
      {
          return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
      }
      Payments payments = db.PaymentsList.Find(id);
      if (payments == null)
      {
          return HttpNotFound();
      }
      return View();
  }

编辑控制器(POST)

 [HttpPost]
 [ValidateAntiForgeryToken]
 public ActionResult Edit([Bind(Include = "PaymentsId,Paymentnumber,PaymentDate,Amount,Discount,Reference,Total")] Payments payments)
 {
     if (ModelState.IsValid)
     {
         db.Entry(payments).State = EntityState.Modified;
         db.SaveChanges();
         return RedirectToAction("Index");
     }
     return View(payments);
 }

您应该在 PaymentsCreate 函数中添加来自 model.SelectedClient 的 ClientsId 初始化,例如:ClientsId = model.SelectedClient。然后您需要将 SelectedClient 字符串添加到 Create (post) 方法中的属性枚举中,以 Bind(Include.... attribute