【问题标题】:How to get the data from a selected value in a view .NET Core API?如何从视图 .NET Core API 中的选定值中获取数据?
【发布时间】:2021-04-12 02:14:55
【问题描述】:

我正在创建一个应用程序,用户可以在其中发布信息并查看发布的信息,类似于论坛。我创建了一个列表,其中显示了存储在数据库中的出版物,因此在主页上显示了每个出版物的标题、描述、日期等列表。现在,我要做的是选择列表中的任何帖子,然后在其他视图中显示所选帖子的完整信息。我正在使用 MVC 视图及其各自的控制器来使用 API。

API 控制器上用于获取所选帖子信息的代码:

    [HttpGet]
    [Route("seePost")]
    public IActionResult seePost([FromBody] int idSelPost)
    {
        PostContentModel post = new PostContentModel();

        var postContent = db.Content.Find(idSelPost);

        var postInfo = db.Forum.Find(idSelPost);

        post.TittlePost = postInfo.TittlePost;

        post.DescPost = postInfo.DescPost;

        post.CreationDate = postInfo.CreationDate;

        post.Content = postContent.Content;
        
        return Ok(post);
    }

使用上面的代码,我加入了两个不同的表 ContentForum 以仅返回一个具有帖子完整信息的模型,以了解选择的帖子是什么,该方法接收一个整数,该整数是来自列表中显示的所选帖子。我已经使用 Postman 在 JSON 文件上发送数字来测试该方法,但似乎 the JSON value could not converted to System.Int32:

{
   "IdPost":6
}

另外,我试图通过创建一个模型类来做同样的事情,该模型类只有一个 int 变量来存储所选帖子的 id 并将其作为参数传递给 seePost 方法中的模型,但它给出了我是“列的无效名称...” Sqlexception。

所以,我不知道该怎么做,感谢任何帮助。

【问题讨论】:

  • 您需要有一个类似public class SelPost { public int { IdPost {get;set;}}} 的模型类并将其作为[FromBody] SelPost post,然后尝试通过执行post.IdPost 从中获取id

标签: c# .net-core asp.net-core-webapi asp.net-core-5.0


【解决方案1】:

路由

{
   "IdPost":6
}

表示需要接受带有IdPost属性的对象;

public class Post
{
   public int IdPost {get;set;}
}

[HttpGet]
[Route("seePost")]
public IActionResult seePost([FromBody] Post post)
{
   // TODO check if not null
   var id = post.Id;

只需发送号码

6

在 URL 中发送 id。

[HttpGet]
[Route("seePost/{idSellPost}")]
public IActionResult seePost(int idSelPost)
{

"列名无效..."

您的模型似乎与数据库不同步。您需要确认ContentForum 模型都正确映射。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-29
    • 2022-12-12
    • 1970-01-01
    • 2020-06-14
    • 2018-12-16
    • 2018-10-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多