0

I have a view model as shown below

public class SampleViewModel
    {
        public Model1 Property1 { get; set; }
    }

public class Model1
{
    [Required]
    public string Name{get; set;}
}

In View We have

@Html.DisplayFor(m=>m.Model1.Name)
@Html.ValidationMessageFor(m=>m.Model1.Name)

In Controller we have

public ActionResult Index()
{
     Model1 a= new Model1();
     SampleViewModel s= new SampleViewModel();
     s.Property1=a;
     return View(s);
}

When Name is null ModelState is not getting populated with model errors even though I have Required attribute for Name. Where am I doing wrong?

Jay
  • 59
  • 1
  • 8

1 Answers1

0

To make this work you should at least create some <input> tag. For example to use the Html.TextBoxFor():

@Html.ValidationSummary(true)

@Html.DisplayFor(m => m.Property1.Name)
@Html.ValidationMessageFor(m => m.Property1.Name)

<p>@Html.TextBoxFor(m => m.Property1.Name)</p>
<br />
<input type="submit" value="Submit " />

The problem can be discovered if you look at the HTML generated by the MVC. The @Html.TextBoxFor(m => m.Property1.Name) is rendered to the following markup:

<input data-val="true" data-val-required="The Name field is required." id="Property1_Name" name="Property1.Name" type="text" value="" />

With the data-val-required attribute the posted page is validated correctly and the ModelState.IsValid returns false when no data entered.

Or you can use:

@Html.HiddenFor(m => m.Property1.Name)

Similar problem is described here: Required string attribute with null value gives IsValid=true in ASP.NET Core 2 Razor Page

Jackdaw
  • 7,626
  • 5
  • 15
  • 33