0

I have a ViewModel defined like this:

public class ProfileSnapshotViewModel
{
    public Guid ProfileSnapshotId { get; set; }
    [Required(AllowEmptyStrings = true)]
    public string Salutation { get; set; }
    //...
    public bool IsActive { get; set; }
}

And my MVC is set like this:

<td class="Cell">
    @Html.HiddenFor(model => model.ProfileSnapshotId)
    @Html.HiddenFor(model => model.IsActive)
    @Html.HiddenFor(model => model.Salutation)
    //...

When I set up the model I set it up like this:

 return PartialView("_additionalreviewerrow",
            new ProfileSnapshotViewModel
            {
                IsActive = true,
                Salutation = ""
            });

However, my ModelState.IsValid continues to be false when submitting, saying 'Salutation is required'.

What can I do to ensure the HiddenFor is holding the empty string, and validation doesn't complain?

(This is part of a larger chunk of code, so if you think something else could be affecting it, please comment and I'll try to add it.)

Renan Araújo
  • 3,533
  • 11
  • 39
  • 49
M Kenyon II
  • 4,136
  • 4
  • 46
  • 94
  • if it's required then you cant have empty string.. if it can be empty then dont make it required.. if you want blanks in the database then add a default value of '' – JamieD77 Nov 11 '15 at 17:34
  • Empty string is different than NULL. We do not want NULL. – M Kenyon II Nov 11 '15 at 17:37
  • 1
    https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.requiredattribute.allowemptystrings(v=vs.110).aspx read the remarks – JamieD77 Nov 11 '15 at 17:42
  • I think your model somewhere must indicate that field is required. If I'm understanding correctly this is my best guess, otherwise try model.IsActive.ToString() and see what happens. – Rich Bianco Nov 11 '15 at 18:22

0 Answers0