如何使用textboxfor和validationmessagefor正确显示客户端验证

时间:2019-07-10 12:26:33

标签: c# razor asp.net-core-mvc

我在显示验证正确性时遇到问题。

我的客户端中包含以下代码。

            @Html.TextBoxFor(m => m.Name, new { id = "MyId", @required = "required", @placeholder = "Name", @class = "valid" })
            @Html.ValidationMessageFor(m => m.Name)

我的模型包含用户名。因此,一旦发布,它就会说“ Micheal”之类的东西。但是以某种方式,我的验证并没有解决这个问题。除非我输入其他内容,否则它仍会显示该消息。

my model is a simple model containing [Required]
    public string Name { get; set; }

我所看到的问题是textboxfor的标准html类是

Picture of html class

这是我的表格

        @using (Html.BeginForm("UserConfirmed", "Login", Model, FormMethod.Post))
    {

    <div class="col-padding">
        <p class="bold-text green">@SharedLocalizer["LabelConfirmUser"]</p>

        <p class="bold-text green userName">@Model.Name</p>

        <a class="btn space-xs-up" onclick="ChangeUser()">@SharedLocalizer["LabelChangeUser"]</a>
        @*<a class="btn space-xs-up" href="@Url.Action("Index", "Login")">@SharedLocalizer["LabelCancel"]</a>*@

        @*<a class="btn space-xs-up pull-right login" type="submit" value="Login">@SharedLocalizer["LabelConfirm"]</a>*@
        <input class="btn space-xs-up pull-right login" value="@SharedLocalizer["LabelConfirm"]" type="submit" />
        <div id="TypeNewUserName" class="field-group" style="display:none">
            <label class="text-green">@SharedLocalizer["LabelNewUser"]</label>
            @Html.TextBoxFor(m => m.Name, new { id = "MyId", @required = "required", @placeholder = "Name"})
            @Html.ValidationMessageFor(m => m.Name)
        </div>
    </div>

    }

1 个答案:

答案 0 :(得分:0)

在@ html.TextBoxFor内部将@required更改为必填

@Html.TextBoxFor(m => m.Name, new { id = "MyId", required = "required", @placeholder = "Name"})