从Get方法传递模型到Post方法时ProductId与UserId被置空
问题解决:Post方法接收模型时ProductId和UserId被置空
原因分析
表单提交时,只有Comment和Rating字段会被传递到后台,ProductId和UserId没有对应的表单元素,所以模型绑定会将这两个字段设为空值。
解决方案
方案1:添加表单隐藏字段
在<form>内部新增两个隐藏输入框,将ProductId和UserId的值随表单一起提交:
<form asp-action="AddReview" method="post"> <!-- 新增隐藏字段传递ProductId和UserId --> <input asp-for="ProductId" type="hidden" /> <input asp-for="UserId" type="hidden" /> <!-- 原有评论和评分字段 --> <div class="mb-3"> <label asp-for="@Model.Comment" class="form-label">Comment</label> <input asp-for="@Model.Comment" class="form-control" aria-required="true" /> <span asp-validation-for="Comment" class="text-danger"></span> </div> <div class="mb-3"> <label asp-for="@Model.Rating" class="form-label">Rating</label> <input asp-for="@Model.Rating" class="form-control" aria-required="true" /> <span asp-validation-for="Rating" class="text-danger"></span> </div> <div class="mb-3"> <input class="btn btn-primary" type="submit" value="Submit Review" /> </div> </form>
方案2:在Post方法中重新获取(更安全)
UserId可以直接从当前用户的Claims中重新获取,避免前端传递带来的篡改风险;ProductId通过路由参数传递:
- 修改Post方法的路由定义,接收ProductId参数:
[HttpPost("{id}")] public async Task<IActionResult> AddReview(int id, AddReviewViewModel addReviewViewModel) { if (!ModelState.IsValid) { // 返回视图前重新赋值,保证页面数据完整性 addReviewViewModel.ProductId = id; addReviewViewModel.UserId = User.FindFirstValue(ClaimTypes.NameIdentifier); return View(addReviewViewModel); } // 业务逻辑中直接使用id作为ProductId,从Claims获取UserId var userId = User.FindFirstValue(ClaimTypes.NameIdentifier); // ...后续业务处理 }
- 调整表单的
asp-action,带上ProductId路由参数:
<form asp-action="AddReview" asp-route-id="@Model.ProductId" method="post"> <!-- 原有评论和评分字段 --> <div class="mb-3"> <label asp-for="@Model.Comment" class="form-label">Comment</label> <input asp-for="@Model.Comment" class="form-control" aria-required="true" /> <span asp-validation-for="Comment" class="text-danger"></span> </div> <div class="mb-3"> <label asp-for="@Model.Rating" class="form-label">Rating</label> <input asp-for="@Model.Rating" class="form-control" aria-required="true" /> <span asp-validation-for="Rating" class="text-danger"></span> </div> <div class="mb-3"> <input class="btn btn-primary" type="submit" value="Submit Review" /> </div> </form>
关于之前添加新产品无问题的说明
添加新产品的场景中,要么表单包含了对应的必填字段,要么在Post方法中通过路由、重新获取等方式填充了字段值,因此未出现空值情况。
内容的提问来源于stack exchange,提问作者JustSoni
相关产品推荐
相关产品推荐

