从get方法传递模型到post将模型为空

  • 本文关键字:模型 post 方法 get c# asp.net
  • 更新时间 :
  • 英文 :


当我将模型传递给post方法上的视图时,ProductId和UserId将被清空。

[HttpGet]
public async Task<IActionResult> AddReview(int id)
{
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
var model = new AddReviewViewModel()
{
ProductId = id,
UserId = userId
};
return View(model);
}
[HttpPost]
public async Task<IActionResult> AddReview(AddReviewViewModel addReviewViewModel)
{
if (!ModelState.IsValid)
{
return View(addReviewViewModel);
}
//...
}

下面是我如何调用post方法。


<div class="row">
<div class="col-sm-12 offset-lg-2 col-lg-8 offset-xl-3 col-xl-6">
<form asp-action="AddReview" 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>
</div>
</div>

我在添加新产品时也做过类似的事情,但没有任何问题。

必须返回数据。它需要往返。这通常是通过隐藏的输入字段完成的。

<input type="hidden" id="ProductId" name="ProductId" value="@Model.ProductId">
<input type="hidden" id="UserId" name="UserId" value="@Model.UserId">

完整的示例

<form asp-action="AddReview" method="post">
<input type="hidden" id="ProductId" name="ProductId" value="@Model.ProductId">
<input type="hidden" id="UserId" name="UserId" value="@Model.UserId">
<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">Comment</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>

如果你的版本支持标签助手,你也可以这样写:

<input type="hidden" asp-for="ProductId">
<input type="hidden" asp-for="UserId">
或者使用HtmlHelper:
@Html.HiddenFor(m => m.ProductId)
@Html.HiddenFor(m => m.UserId)

在任何情况下,请确保将此添加到表单中。

最新更新