动态显示Razor ValidationMessageFor

时间:2017-05-08 16:07:07

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

我在页面顶部进行了一些验证。我想只在有错误的情况下动态显示水平行。

<tr><td colspan="4">@Html.ValidationMessageFor(model => model.tempHouseHoldSSNVerification, null, new { style = "color:red" })</td></tr>
<tr><td colspan="4">@Html.ValidationMessageFor(model => model.tempHouseHoldCitizenVerification, null, new { style = "color:red" })</td></tr>

我想要做的是在Razor语法中有这样的东西

@if (model.tempHouseHoldSSNVerification isinvalid)
{  
    <tr><td colspan="4">@Html.ValidationMessageFor(model => model.tempHouseHoldSSNVerification, null, new { style = "color:red" })</td></tr>
 }

我试图找出剃刀中的语法,我可以动态显示水平行。有什么建议??

2 个答案:

答案 0 :(得分:3)

如果您只想在出现错误时显示错误消息。您可以通过ModelState使用ViewContext.ViewData.ModelState验证。

示例:

@if (!ViewContext.ViewData.ModelState.IsValid)
{
   <tr>
    <td colspan="4">@Html.ValidationMessageFor(model => model.tempHouseHoldSSNVerification, null, new { style = "color:red" })
   </td>
  </tr>
}

答案 1 :(得分:0)

请勿将它们视为单独的行。默认情况下,只有在有理由的情况下才会显示验证消息。因此,您可以这样做:

<tr>
    <td colspan="4">
        @Html.ValidationMessageFor(model => model.tempHouseHoldSSNVerification, null, new { style = "color:red" })
        @Html.ValidationMessageFor(model => model.tempHouseHoldCitizenVerification, null, new { style = "color:red" })
    </td>
</tr>

然后,无论哪一个都有验证错误都会显示,而另一个则不会。无需手动检查错误。