show div if unobtrusive validation was invalid and hide it if Valid in MVC 3

Saeid picture Saeid · Apr 22, 2012 · Viewed 10.6k times · Source

This is a part of my Edit view:

<dt>
@Html.LabelFor(model => model.MainModel.StartDate)
</dt>
<dd>
@Html.TextBoxFor(model => model.MainModel.StartDate)
@Html.ValidationMessageFor(model => model.MainModel.StartDate)
    <div class="targetDiv"> My content </div>
</dd>

So as all of you know when StartDate field in my model not valid unobtrusive show the error message and if valid hide it. Now I want to add another action to this process. I need if StartDate value is Invalid show "targetDiv" div and if StartDate value is Valid hide it. what is your suggestion?

Answer

archil picture archil · Apr 22, 2012

You can check for field validity with ModelState.IsValidField method

<div class="targetDiv" @if (Html.ViewData.ModelState.IsValidField("StartDate"))
{
     <text>style="display:none"</text>         
}>
     My content 
</div>