从数据库加入两个表,并在MVC

时间:2017-05-09 10:39:04

标签: c# asp.net-mvc-4 asp.net-mvc-5

我有以下查询 我想连接两个表并在下拉列表中显示一列。

控制器代码:

// GET: SelectLLD
public ActionResult Index()
{

    var sLoginName = Session["LoginName"];
    var iLoginId = Session["LoginID"];

    if(sLoginName!= null)
    {
        ViewBag.LoginId = iLoginId;


        //Db context object 
        enterpriseEntities db = new enterpriseEntities();

        var lob = from l in db.Lobs
                  join r in db.Rights
                  on l.LobID equals r.LobID
                  //where r.LoginID =
                  select new
                  {
                      l.LobName

                  };
        SelectList list = new SelectList (lob, "lobname");

        ViewBag.LobNames = list;
        return View();

    }
    else{

        return RedirectToAction("Index", "Login");
    }


}

查看代码:

@{
    ViewBag.Title = "Index";
}
<h4>Welcome @Session["LoginName"]</h4>
<h4>@ViewBag.LoginId</h4>
<h3>Select LOB</h3>

<div>
    @Html.DropDownList("LobNames", "Select a Value")
</div>
<h3>Select Bussiness Date </h3>

问题在于,使用上面的代码我获取列名也添加了下拉列表中的列值。 以下是截图

我得到的是列名和值。 i am getting the out having column name and the value

我只希望在下拉列表中显示列值。例如,只应显示“Sales”值。

1 个答案:

答案 0 :(得分:0)

您可以将SelectList list = new SelectList (lob, "lobname");代码更改为此类代码吗?

  var list = logb.Select(x => new SelectListItem {
            Value = x.LobID.ToString(),
            Text = x.LobName
        }).ToList();

这意味着你必须将LobId添加到原始选择中,如此

var lob = from l in db.Lobs
                  join r in db.Rights
                  on l.LobID equals r.LobID
                  //where r.LoginID =
                  select new
                  {
                      LobName = l.LobName,
                      LobID = L.LobID
                  };

编辑:假设您希望在提交表单而不是LobName时传递LobID值。