将ModelState错误显示到视图中

问题描述 投票:0回答:1

我正在尝试向用户显示一些错误。

为此,我正在使用ModelState.isValid@Html.ValidationSummary进行显示。

但是以某种方式,它暂时不起作用。

型号:

[Required(ErrorMessage = "Account name is required")]
[EmailAddress]
public string CTC_accountName { get; set; }

[Required(ErrorMessage = "Password is required")]
[DataType(DataType.Password)]
public string CTC_accountPassword { get; set; }

Controller:

[HttpPost]
public async Task<IActionResult> Submit(RegisterViewModel model)
{
        if (!ModelState.IsValid)
        {
          return View(model);
        }
    }
}

视图:

@using (Html.BeginForm("Submit", "Register", FormMethod.Post, new { id = "formAll", style = "margin-top:3%", enctype = "multipart/form-data" }))
{

    <div class="shadow-sm p-2 mb-3 rounded">
        <div class="col-sm-9">
            <h5>Personal Details</h5>
        </div>
    </div>
    <div id="formMember">
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group row">
            <div class="col-sm-2">
                @Html.LabelFor(model => model.CTC_accountName, "Account/Email*")
            </div>
            <div class="col-sm-10">
                @Html.EditorFor(model => model.CTC_accountName, new { htmlAttributes = new { @class = "form-control", @placeholder = "Email", @id = "CTC_accountName", @autocomplete = "username" } })
            </div>
            <div class="col-sm-10">
                 @Html.ValidationMessageFor(model => model.CTC_accountName)
            </div>
        </div>
        <div class="form-group row">
            <div class="col-sm-2">
                @Html.LabelFor(model => model.CTC_accountPassword, "Password*")
            </div>
            <div class="col-sm-10">
                @Html.EditorFor(model => model.CTC_accountPassword, new { htmlAttributes = new { @class = "form-control", @placeholder = "Password", @id = "CTC_accountPassword", @type = "password", @autocomplete = "current-password" } })
            </div>
            <div class="col-sm-10">
                @Html.ValidationMessageFor(model => model.CTC_accountName)
            </div>
        </div>
    </div>
}

感谢您的帮助

c# html asp.net modelstate
1个回答
0
投票

我发现了问题所在。

我在提交功能中有一个POST调用ajax,必须删除才能查看@ Html.ValidationSummary!

© www.soinside.com 2019 - 2024. All rights reserved.