【问题标题】:ASP.NET Populating Dropdown with associated foreign key text valueASP.NET 使用关联的外键文本值填充下拉列表
【发布时间】:2021-01-10 12:27:22
【问题描述】:

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

我的控制器

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>

我的数据库表

我在浏览器上的视图

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

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

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

【问题讨论】:

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


    【解决方案1】:

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

    使用会话存储和使用重定向页面中的用户标识。 或者这个链接会帮助你。 RedirectToAction with parameter

    【讨论】:

    • 如果此答案解决了您的问题或将您重定向到正确的方向,那么请接受此答案。这将有助于将来参考。如果您有任何疑问或难以理解答案,请在此处发表评论。谢谢
    • 谢谢你,我如何获得身份证?到目前为止我已经得到了这个: 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", "controller", new { @id = }); return RedirectToAction("Create", new RouteValueDictionary( new { controller = "controller", action = "Create", Id = id }))
    • var databaseUserProfile = db.UserProfiles.Where(x => x.UserName == log.UserName && x.Password == log.Password); string userId = databaseUserProfile.UserId 会给你 UserId
    • 再次感谢,虽然字符串上的 UserID 给出了此错误 严重性代码 描述 项目文件行抑制状态错误 CS1061 'int' 不包含 'UserID' 的定义并且没有可访问的扩展方法 'UserID'可以找到接受“int”类型的第一个参数(您是否缺少 using 指令或程序集引用?)我该如何解决?
    • var userId = db.UserProfiles.FirstOrDefault(x => x.UserName == log.UserName && x.Password == log.Password).UserID; if condition(count>0) 尝试这个成功
    猜你喜欢
    • 2022-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    相关资源
    最近更新 更多