Search code examples
c#.net-6.0razor-pages

C# RazorPg - Check if form field is empty and mark as unchanged


I have a form field that allows users to change their email address. If the user doesn't enter anything in the field I want to send "unchanged" to the API. Not blank "" or null.

I've came up with this code:

if (!String.IsNullOrEmpty(Request.Form["Email"].ToString()))  // Null or blank check
{
 if (Request.Form["Email"].ToString() != user.Email)  // Don't update email if it's the same as the existing one
  {
    user.Email = Request.Form["Email"];
  }
  else
  {
    user.Email = "unchanged";      // I don't want to pass null or blank to the API.
  }
}
else
{
 user.Email = "unchanged";
}

It just looks very messy to me. I have 10 fields on the page so I'd be listing that 10 times in my controller.

Is there a nicer way of doing this?


Solution

  • I think you can initialize the Email property in your User model :

    public string Email { get; set; } = "unchanged"; 
    

    you can do it also in the default constructor .