ASP.NET 使用关联的外键文本值填充下拉列表

ASP.NET Populating Dropdown with associated foreign key text value

我是 ASP.NET 的新手,目前我正在努力将下拉菜单绑定到关联的外键 table。

我的控制器

public ActionResult Create()
{
    //get current user id 
    ViewBag.UserID = new SelectList(db.UserProfiles, "UserID", "Employer");
    return View();
}

我的观点

<div class="form-group">
  @Html.LabelFor(model => model.UserID, htmlAttributes: new { @class = "control-label col-md-2" })
  <div class="col-md-10">
    @Html.DropDownList("UserID", null, htmlAttributes: new { @class = "form-control" })
    @Html.ValidationMessageFor(model => model.UserID, "", new { @class = "text-danger" })
  </div>
</div>

我的数据库Table

我在浏览器上的视图

我还创建了一个登录名,以便了解哪些用户已登录

[HttpPost]
public ActionResult Index(UserProfile log)
{
    var user = db.UserProfiles.Where(x => x.UserName == log.UserName && x.Password == log.Password).Count();
    if (user > 0)
    {
        return RedirectToAction("Create", "Dashboard");
    }

    else
    {
        return View();
    }
}

总而言之,我希望在下拉列表中看到关联的雇主,因此根据 table 关系将其级联到用户。如果其他雇主与已登录的用户无关,我不想看到他们。实现该目标的最佳方法是什么?

登录成功后,在重定向到下一页时传递用户ID。在下一页中使用该用户 ID 从数据库中获取下拉值(其中 userid=loggedinuserid)。现在你只会得到与当前用户对应的员工。

使用session在重定向页面中存储和使用userid。 或者这个 link 会帮助你。 RedirectToAction with parameter