将ViewModel Validation-Message添加到@ Html.LabelFor中的HTML属性

时间:2017-07-20 12:24:16

标签: asp.net-mvc validation asp.net-core materialize

我想验证具有asp.net core mvc内置功能的表单,但验证消息应该与materializecss的data-error属性很好地一起显示。为了使这项工作,我需要在视图字符串中的消息。

在视图中,我添加了$HydraulicTest = new HydraulicTest(); $HydraulicTest->setTester('This is a test'); $hydraulicTestResult= new HydraulicTestResult(); $HydraulicTest->addHydraulicTestResult($hydraulicTestResult); ... .... $em->persist($hydraulicTestResult); $em->persist($HydraulicTest); $em->flush(); jquery.validate.js。两者都正确加载。表格将与jquery ajax一起提交。要使验证工作,提交按钮会执行 AJAX 调用并阻止提交操作。

通常情况下,我会在View(可行)中写出类似的内容:

jquery.validate.unobtrusive.js

但我想将验证消息设置为数据错误HTML属性,以便将其设置为materializecss。

所以我试过了:

@Html.TextBoxFor(model => model.Email, "", new { @id = "EMail", @type = "email", @class = "validate" })
@Html.LabelFor("E-Mail Address", null, new { @for = "EMail"})
@Html.ValidationMessageFor(model => model.Email)

总是给我“Microsoft.AspNetCore.Mvc.Rendering.TagBuilder”作为错误消息。

如何在@Html.TextBoxFor(model => model.Email, "", new { @id = "EMail", @type = "email", @class = "validate" }) @Html.LabelFor("E-Mail Address", null, new { @for = "EMail", data_error = Html.ValidationMessageFor(model => model.Email) }) 方法中将验证邮件从ViewModel设置为data-error html-attribute?

要清除,这是我的ViewModel:

@Html.LabelForModule

1 个答案:

答案 0 :(得分:0)

您可以通过css和MaterializeCSS显示data-error attribute之类的错误消息。

HTML输入:

<div class="input-field col s12">
    @Html.TextBoxFor(model => model.Email, "", new { @id = "EMail", @type = "email",     
    @class = "validate" })
    @Html.LabelFor("E-Mail Address", null, new { @for = "EMail"})
    @Html.ValidationMessageFor(model => model.Email)
</div>

的CSS:

.field-validation-error span {
    color: inherit;
    display: block;
    position: absolute;
    right: 0;
    top: 100%;
    transition: .2s opacity ease-out, .2s color ease-out;
    -webkit-transition: .2s opacity ease-out, .2s color ease-out;
}

Css Validation