asp.net 将模型从get方法传递到post会使模型为空

lmvvr0a8  于 2022-12-15  发布在  .NET
关注(0)|答案(1)|浏览(140)

当我通过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>

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

qhhrdooz

qhhrdooz1#

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

<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>

如果您的版本支持taghelper,您还可以编写:

<input type="hidden" asp-for="ProductId">
<input type="hidden" asp-for="UserId">

或者使用HtmlHelper:

@Html.HiddenFor(m => m.ProductId)
@Html.HiddenFor(m => m.UserId)

在任何情况下,都要确保在表单内部添加此内容。

相关问题