如何显示外键值从一个模型级联下拉列表在mvc5

How to display foreign key value from a model to a cascaded dropdown list in mvc5?

本文关键字:级联 模型 一个 下拉列表 mvc5 何显示 显示 键值      更新时间:2023-09-26

我仍然是mvc5的新手,对javascript的了解很少。我知道我的级联工作,但我有麻烦的显示部分。我想做的是有两个下拉列表。第一个包含所有客户的姓名,第二个将包含他们的未决交易列表。基本上第一个下拉菜单将有客户的名字,而第二个将有视频标题。请检查我的代码,我做错了。为什么我不能显示视频标题。顺便说一句,我在交易中尝试了其他属性,我可以显示它们。这就是为什么我知道我的级联不是问题。

模型
//Transaction Model
TransactionID { get; set; }
public int CustomerID { get; set; }
public virtual Customers CustomerName { get; set; }
public int VideoID { get; set; }
public virtual Videos Videos { get; set; }
public int Quantity { get; set; }
[ReadOnly(true)]
public DateTime? TransactionDate { get; set; }
[ReadOnly(true)]
public DateTime? DueDate { get; set; }
[ReadOnly(true)]
public Decimal Cost { get; set; }
[ReadOnly(true)]
public String ReturnStatus { get; set;}
//Customers Model
public int CustomerID { get; set; }
public string CustomerName { get; set; }
public string CustomerAddress { get; set; }
public string CustomerContact { get; set; }
//Video Model
public int VideoID { get; set; }
public string VideoTitle { get; set; }
public int CategoryID { get; set; }
public virtual Category VideoCategory { get; set; }
[Range(0,99)]
public int VideoIn { get; set; }
[Range(0,99)]
public int VideoOut { get; set; }

控制方法

public ActionResult CustomerList()
{
   var customers = db.Customers.OrderBy(x => x.CustomerID).ToList();
    if (HttpContext.Request.IsAjaxRequest())
    {
        return Json(new SelectList(
                    customers,
                    "CustomerID",
                    "CustomerName"), JsonRequestBehavior.AllowGet
                    );
    }
    return View(customers);
}
public ActionResult Transact(int cusId)
{
    var transact = db.Transactions
                     .Where(x => x.CustomerID == cusId)
                     .Where(s => s.ReturnStatus == "FALSE").ToList();
    if (HttpContext.Request.IsAjaxRequest())
        return Json(new SelectList(
                        transact,
                        "TransactionID",
                        "VideoTitle"), JsonRequestBehavior.AllowGet
                    );
    return View(transact);
}

经过几个小时的试错,我想出了一个解决方案。我所做的就是在我的查询中添加了一个join。

var transact = db.Transactions
                        .Where(x => x.CustomerID == cusId)
                        .Where(s => s.ReturnStatus == "FALSE")
                        .Join(db.Videos,
                        v => v.VideoID,
                        t => t.VideoID,
                        (transaction, videos) => new { 
                        TransactionID = transaction.TransactionID,
                        VideoTitle = videos.VideoTitle }).ToList();