如何使用Html.Validate将警报消息用于验证错误

时间:2013-08-19 05:55:09

标签: asp.net-mvc asp.net-mvc-3 asp.net-mvc-4 razor

如何使用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);}
}

1 个答案:

答案 0 :(得分: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 -->
}

希望它有所帮助。