如何在mvc5中将模型中的外键值显示为级联下拉列表?

时间:2016-10-08 15:01:17

标签: javascript c# json asp.net-mvc asp.net-mvc-5

我还是mvc5的新手,对javascript知之甚少。我知道我的级联工作但是我的显示部分有问题。我想要做的是有2个下拉列表。 1包含所有客户名称,第2个将包含其待处理事务的列表。基本上第一个下拉列表将有客户名称,而第二个下拉列表将有视频标题。请检查我的代码我做错了什么。为什么我无法显示视频节目。顺便说一下,我在交易中尝试了其他属性,我可以显示它们。这就是我如何知道我的级联不是问题。

模型

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

1 个答案:

答案 0 :(得分:0)

我在试用数小时后找出了一个错误的解决方案。我所做的是在查询中添加了一个连接。

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