ValidationMessage not showing up when using more than one model

392 views Asked by At

I have the form that uses 2 models so I include that this way:

@model Equipment.Models.PublicViewModel

where PublicViewModel is

namespace Equipment.Models
{
    public class PublicViewModel
    {
        public Device Devices { get; set; }
        public UserCredentials Data { get; set; }
    }
}

For example UserCredential class looks like:

namespace Equipment.Models
{
    public class UserCredentials
    {
        [Required]
        public string UserName { get; set; }
        [Required]
        public string Password { get; set; }
    }
}

and my form:

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    <hr />
        @Html.ValidationSummary(true)

        <div class="input-group">
            @Html.LabelFor(model => model.Data.UserName, new { @class = " input-group-addon" })
            @Html.TextBoxFor(model => model.Data.UserName, new { @class = "form-control" })<br />
            @Html.ValidationMessageFor(model => model.Data.UserName)
        </div>

        ...

        <div class="input-group">
            @Html.LabelFor(model => model.Devices.DeviceSerialNumber, new { @class = " input-group-addon" })
            @Html.TextBoxFor(model => model.Devices.DeviceSerialNumber, new { @class = "form-control" })<br />
            @Html.ValidationMessageFor(model => model.Devices.DeviceSerialNumber)
        </div>
        ...
}

In other form when I use only one model everything works. Can anyone tell me why this isn't working for 2 models?

1

There are 1 answers

0
Nitin Varpe On BEST ANSWER

From this LINK its confirmed that you can't have client side validation on nested objects. Only property level validators can emit client-side validation.

So rather the using DataAnnotations you could use FluentValidation.NET as stated by @Darin on this link

Still other way you can choose is to have separete partial view for both the models and calling those views from single view and passing models as needed to these views.

Like this

<div class="input-group">
        @Html.Partial("ViewForModelData", Model.Data)
        </div>


        <div class="input-group">
         @Html.Partial("ViewForModelDevice", Model.Device)
        </div>

Then you can have separate Validation summary in both these views!