隐藏输入 Razor c# 中的错误值

wrong value in hidden input Razor c#

我有模型属性int? CaseId

public class TaskDetailsVm
{
    public TaskDetailsVm(Task task)
    {
        CaseId = task.CaseID;
    }

    public int? CaseId { get; set; }
}

并在视图中:

@Html.HiddenFor(x => x.CaseId) => 0
@Html.Hidden("CaseId", Model.CaseId) => 0
@Html.Hidden("qwe", Model.CaseId) => real value
<input type="hidden" id="CaseId" name="CaseId" value="@Model.CaseId" /> => real value

在浏览器中我看到了这个:

<input data-val="true" data-val-number="The field CaseId must be a number." id="CaseId" name="CaseId" type="hidden" value="0">
<input id="CaseId" name="CaseId" type="hidden" value="0">
<input id="qwe" name="qwe" type="hidden" value="22906">
<input type="hidden" id="CaseId" name="CaseId" value="22906">

为什么我可以看到以下内容?我没有看到任何脚本来覆盖此值。我该如何解决? 同样对于第一行代码,由于某些我无法理解的原因,我看到了额外的属性 data-val="true"data-val-number="The field CaseId must be a number."

这与ModelState有关。根据这个 article:

ASP.NET MVC assumes that if you’re rendering a View in response to an HTTP POST, and you’re using the Html Helpers, then you are most likely to be re-displaying a form that has failed validation. Therefore, the Html Helpers actually check in ModelState for the value to display in a field before they look in the Model. This enables them to redisplay erroneous data that was entered by the user, and a matching error message if needed. Since our [HttpPost] overload of Index relies on Model Binding to parse the POST data, ModelState has automatically been populated with the values of the fields. In our action we change the Model data (not the ModelState), but the Html Helpers (i.e. Html.Hidden and Html.TextBox) check ModelState first… and so display the values that were received by the action, not those we modified.

现在在这种情况下:@Html.HiddenFor(x => x.CaseId, new {Value = @Model.CaseId}),因为您明确定义了当前 Model 的值,它会显示您期望的值。您可以在您的 Controller 中使用 ModelState.Clear(); 在您的 POST 之后在表格上重设模型值。