Search code examples
asp.net-mvc-4foolproof-validation

MVC Foolproof not working for DisplayTextFor


I have a conditional requirement:

 [Display(Name = "Contract Number:")]
    [RequiredIf("CandidateType", "Contractor")]
    public string ContractNumber { get; set; }

And in the view:

 @Html.DisplayTextFor(x => x.CandidateType)

 <td>
                    @Html.DisplayNameFor(x=>x.ContractNumber)<br />
                    @Html.ValidationMessageFor(x=>x.ContractNumber)
                </td>
                <td>
                    @Html.TextBoxForWithTitle(x=>x.ContractNumber, new { @id = "txtContractNumber", @class = "textNormal"})
                </td>

But the validation fails because the display for helper does not have the name of the field. How do you fix this? It works if I use TextBoxFor and set it to readonly, but it looks silly.


Solution

  • You can add a hidden input for the value

    @Html.HiddenFor(x => x.CandidateType)
    

    or style the element created by TextBoxFor() to remove the borders, padding etc. if you want to appear to to look like the element created by DisplayTextFor()