0

如何使用 Html Validate 或 Html ValidateFor 显示错误警报

<script type="text/javascript">
    $(document).ready(function () {
        $("#RegisterForm").bind('invalid-form.validate',
    function (event, validator) {
    alert(validator.errorMap.FName);
    console.log(validator.errorMap);
    });
    });
</script>


@using(Html.BeginForm()){
    <span>First Name: </span>@Html.TextBoxFor(model => model.FName)
    @{Html.ValidateFor(model => model.FName);}
}
4

1 回答 1

0

您可以尝试像这样扩展验证摘要:

public static class ValidationSummaryAlert
{
    public static string ValidationSummaryWithAlert(this HtmlHelper ext)
    {
        if (!ext.ViewData.ModelState.IsValid)
        {
            var alertMessage = (from item in ext.ViewData.ModelState
                                where item.Value.Errors.Any()
                                  && item.Key.Equals("Popup")
                                select new { Message = item.Value.Errors[0].ErrorMessage, item.Key }).SingleOrDefault();

            return
                string.Format(
                    "<script language=\"javascript\" type=\"text/javascript\">$(function() {{alert('{0}')}});</script>",
                    alertMessage);
        }

        return string.Empty;
    }
}

然后在视图中:

@using(Html.BeginForm()){
    @Html.Raw(Html.ValidationSummaryWithAlert())

    <!-- YOUR CODE -->
}
于 2013-08-19T06:49:24.893 回答