【问题标题】:How do I get the user id from my database and display it using ASP.NET Core MVC如何从我的数据库中获取用户 ID 并使用 ASP.NET Core MVC 显示它
【发布时间】:2021-08-03 13:39:57
【问题描述】:

这是我的操作方法:

[HttpGet]
[Route("{userId}")]
public IActionResult Show(int userId)
{
    List<Dictionary<string, object>> User = DbConnector.Query($"SELECT * FROM users WHERE id = {userId}");
    ViewBag.userId = 1;
    return View();
}

这是我的index.cshtml 文件:

<h1>here is one user:</h1>
<h3>@ViewBag.userId</h3>

我认为我在控制器中做错了什么,但我不确定是什么。

【问题讨论】:

  • 请注意,将字符串连接与内联 SQL 一起使用是有风险的,通常是不必要的。根据您的提供商,应该有一种方法来提供参数。此外,使用SELECT * 通常是一种不好的形式。否则,你为什么要使用ViewBag?为什么不使用return View(User); 并将您的cshtml 更改为顶部有@model List&lt;Dictionary&lt;string, object&gt;&gt;,然后在数据中找到您的用户ID。我不确定您为什么使用 List&lt;Dictionary&lt;string, object&gt;&gt; 来捕获结果,但如果您需要帮助,您需要提供该结构如何填充的示例数据。
  • @aquile hollins:最好使用ORM(对象-关系映射)技术并定义可能传递给视图的数据模型(MVC pattern)。

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


【解决方案1】:

如下所示。

定义您的User 数据模型:

public class User
{
    [Display(Name = "User Id")]
    public int UserId { get; set; }

    // Another properties ...
}

在控制器中:

[HttpGet]
[Route("{userId}")]
public IActionResult Show(int userId)
{
    User user = /* obtain the user record from the db */

    // Pass the user to the strongly typed view.
    return View(user);
}

show.cshtml

@model Models.User

<!DOCTYPE html>
<html>
<body>
    <div class="column">
        @Html.DisplayForModel()
    </div>  
</body>
</html>

【讨论】:

  • 哦,好吧,从那以后赚了这么多!我忘了定义我的模型!谢谢你是个传奇。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-20
  • 2021-04-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多