In older c#, I would have a ViewModel like this:
public Class MyViewModel
{
[Required]
public string FirstName { get; set; }
public string MiddleName { get; set; }
[Required]
public string LastName{ get; set; }
}
then in my controller:
var model = new MyViewModel();
return View(model);
(I know you might just not pass a ViewModel into the View on GET, but imagine I need to to set other properties).
Now in newer c#, I’m doing this instead:
public Class MyViewModel
{
public required string FirstName { get; set; }
public string MiddleName { get; set; }
public required string LastName{ get; set; }
}
But now the compiler won’t let create new MyViewModel()
anymore, because I have to set the required properties. I understand why, because that’s how required
works. But I don’t want to set any initial values for those properties; because I want the user to fill them out on the form/View. They’re “required” because I want the built-in validation that won’t let them submit.
I can get around this by initializing them all to empty string; either in the ViewModel itself or in the controller when I instantiate the class. But this seems almost like a hack, or at the least it leads to ugly code. Is there a proper/expected way to do this?
2