昨天我花了很多时间搜索和解决这个问题,但没有找到解决方案。 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 获取数据。
Browse.cshtml 缺少@addTagHelpers...我添加了以下内容:
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers @addTagHelper *, AuthoringTagHelpers
我的 CollectController.cs 缺少一条路线...我添加了以下内容:
[HttpPost, ValidateAntiForgeryToken] [Route("Index/Collect")]
最后,我将我的 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/