View传递StoreLicenseId至Controller时参数始终为空问题排查
问题:ASP.NET Core表单提交时路由参数无法传递,控制器参数始终为null
我有一个已填充数据的DataTable,尝试将其中的StoreLicenseId通过表单提交传递到Controller的TerminalInfo方法,但该方法的storeLicenseId参数始终返回null,所有配置看似正常但功能无法运行。
视图代码
<form method="post"> <input class="btn btn-outline-info btn-1" type="submit" value="Terminal" asp-controller="Terminal" asp-action="TerminalInfo" asp-route-id="@item.StoreLicenseId"> </form>
控制器代码
public IActionResult TerminalInfo(string storeLicenseId) { if (_context.StoreLicenses == null) { return NotFound(); } var terminalModel = _context.StoreLicenses.FindAsync(storeLicenseId); if (terminalModel == null) { return NotFound(); } return View(terminalModel); }
问题原因
核心问题是路由参数名称与控制器参数不匹配:
你在视图中使用asp-route-id,会生成名为id的路由参数,但控制器方法接收的参数是storeLicenseId,ASP.NET Core无法自动映射这两个不同名称的参数,因此导致storeLicenseId始终为null。
另外,原控制器代码还有一个隐藏bug:FindAsync是异步方法,未添加await关键字时,terminalModel实际是Task<StoreLicense>类型对象,永远不会为null,导致后续的NotFound判断永远不会触发。
解决方案
方案1:修改视图的路由参数名称(推荐)
将asp-route-id改为asp-route-storeLicenseId,让路由参数名称与控制器参数完全匹配:
<form method="post"> <input class="btn btn-outline-info btn-1" type="submit" value="Terminal" asp-controller="Terminal" asp-action="TerminalInfo" asp-route-storeLicenseId="@item.StoreLicenseId"> </form>
方案2:修改控制器参数匹配路由名称
如果不想改动视图,可以通过两种方式让控制器参数匹配路由中的id:
- 直接修改参数名为
id:
public async Task<IActionResult> TerminalInfo(string id) { if (_context.StoreLicenses == null) { return NotFound(); } var terminalModel = await _context.StoreLicenses.FindAsync(id); if (terminalModel == null) { return NotFound(); } return View(terminalModel); }
- 使用
[FromRoute]特性指定路由参数名称:
public async Task<IActionResult> TerminalInfo([FromRoute(Name = "id")] string storeLicenseId) { if (_context.StoreLicenses == null) { return NotFound(); } var terminalModel = await _context.StoreLicenses.FindAsync(storeLicenseId); if (terminalModel == null) { return NotFound(); } return View(terminalModel); }
必须修复的异步方法问题
无论采用哪种方案,都要将控制器方法改为异步并添加await关键字,否则FindAsync的结果判断会失效:
- 方法返回值改为
Task<IActionResult> - 在
FindAsync前添加await
内容的提问来源于stack exchange,提问作者SheUsesVaseline
相关产品推荐
相关产品推荐

