c# - ASP.NET Core 2.1 Razor Form,Post 未到达 Controller

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

昨天我花了很多时间搜索和解决这个问题,但没有找到解决方案。 Here is the guide I used as reference.

问题是表单中的数据没有到达我的 Controller 。我的目标是获取表单数据并将其传递给我的 Controller /模型,以便我可以在整个代码中使用这些值并将它们存储在数据库中。以下是我目前所拥有的...

在我的 Browse.cshtml( View )中

@model Collect

<form asp-action="Collect" asp-controller="Collect" method="post">
<input type="hidden" asp-for="GameId" name="@game.id"/>
<button type="submit" class="dropdown-item btn btn-block">Default</button>
</form>

在我的 CollectController.cs( Controller )中

using System;
using GameLibrary.me.Models;
using Microsoft.AspNetCore.Mvc;

namespace GameLibrary.me.Controllers
{
public class CollectController  : Controller
{
    [HttpGet]
    public IActionResult Collect()
    {
        return View();
    }

    [HttpPost, ValidateAntiForgeryToken]
    public IActionResult Collect(Collect model)
    {

        Console.WriteLine("**********\n"+model.GameId+"\n**********");

        return Content($"Hello {model.GameId}");
    }    
  }
}

在我的 Collect.cs(模型)中

namespace GameLibrary.me.Models

{
public class Collect
{
    public int GameId { get; set; }
  }
}

编辑:这是我的 IDE 告诉我的...

info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
  Request starting HTTP/1.1 POST https://localhost:5001/browse?game=eevee application/x-www-form-urlencoded 7

info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
  Request finished in 1.0139ms 200

info: Microsoft.AspNetCore.Server.Kestrel[32]
  Connection id "0HLJHIUOU6AKO", Request id "0HLJHIUOU6AKO:00000003": the application completed without reading the entire request body.

任何关于我做错了什么的指导将不胜感激...我也可以通过隐藏字段类型发送多个值,还是应该为每个值创建一个新的隐藏字段类型?

最佳答案

这里有很多不同的帮助,尤其要感谢 Kirk Larklin!有三个问题阻止我的 Controller 获取数据。

  1. Browse.cshtml 缺少@addTagHelpers...我添加了以下内容:

    @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
    @addTagHelper *, AuthoringTagHelpers
    
  2. 我的 CollectController.cs 缺少一条路线...我添加了以下内容:

    [HttpPost, ValidateAntiForgeryToken]
    [Route("Index/Collect")] 
    
  3. 最后,我将我的 Controller post 方法从与另一个方法冲突的“Collect”重命名为 Index,并更新了我的 Browse.CSHTML 文件中的 asp-action 以匹配。

    public IActionResult Index(Collect model)
    

感谢大家的帮助!

-特拉维斯W

关于c# - ASP.NET Core 2.1 Razor Form,Post 未到达 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54026020/

相关文章:

c# - 如何从 C# 中的 HTML 页面中提取关键字?

c# - UnauthorizedAccessException 与 Zip 存档中临时文件夹中的文件路径

c# - 限制 File.Copy 的速度

asp.net-mvc-3 - 将 Google 图表 API 与 MVC 3 Razor 和 jquery ajax 结合使用

jquery - Controller 中的参数在 asp.net mvc 中给出空值异常

c# - 无授权 header

c# - 清理从 MS Word 粘贴的内容

c# - MVC 5 使用 actionlink 将模型从 View 传递到 Controller

asp.net-mvc - 与 jquery 选项卡一起使用时,Html.Actionlink 显示错误的 Controller 名称

c# - asp .net core 中的自动 Controller 检测