0

In my MVC4 application. I've got a view-model called SixweekRangeViewModel

public class SixweekViewModel: IValidatableObject
{
    public int Position { get; set; }
    public DateTime? StartDate { get; set; }
    public DateTime? EndDate { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (StartDate.HasValue || EndDate.HasValue)
        {
            if (!StartDate.HasValue || !EndDate.HasValue)
            {
                yield return new ValidationResult("*");
                // new string[] { "StartDate", "FinalDate" }
            }
        }
    }
}

And this is my view where I display the items

@model List<Contoso.MvcApplication.ViewModels.Assignments.SixweekViewModel>

<h2>Configure Sixweeks</h2>

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Configure Sixweeks</legend>

        @for (int i = 0; i < Model.Count; i++) {
        <div>
            @Html.HiddenFor(model => model[i].Position)

            @Html.TextBoxFor(model => model[i].StartDate, "{0:d/MMM/yyyy}", new { @class = "from" + i })
            @Html.TextBoxFor(model => Model[i].EndDate, "{0:d/MMM/yyyy}", new { @class = "to" + i })
        </div>
        }

        <p>
            <input type="submit" value="Save" />
        </p>
    </fieldset>
}

When I press Save, the debugger get the validationResult as an error. But never show it the error messages at the view.

I supposed that IValidatableObject should be implemented in the List<T> and not for T object, but this just an idea. What am I missing people?

tereško
  • 58,060
  • 25
  • 98
  • 150
Darf Zon
  • 6,268
  • 20
  • 90
  • 149

1 Answers1

0

You can implement the IValidateObject for any classes [Models] not for lists alone. You should return the key and its corresponding values. Since you have returned only "*" as the key, the values [error messages] are not shown to you. Please check this link

Saravanan
  • 7,637
  • 5
  • 41
  • 72