0

I have 5 plus elements in a view. Is there a cleaner way to check for nulls and set the values if they are before saving in my controller? For example:

string FN = viewModel.FirstName;
if (String.IsNullOrEmpty(FN))
{
    FN = "N/A";
}
//copy and paste for lastname
//copy and paste for address
//etc
Skullomania
  • 2,225
  • 2
  • 29
  • 65
  • 2
    `string FN = !String.IsNullOrEmpty(viewModel.FirstName) ? viewModel.FirstName : "N/A";` is one option. *Ceaner* is subjective tho. – Kirk Larkin Nov 15 '17 at 21:07
  • 1
    @Kirk, I didnt think about using a tenary. Post as an answer and I will give you credit as you were the first – Skullomania Nov 15 '17 at 21:10
  • Probably better to close it as a duplicate. – Kirk Larkin Nov 15 '17 at 21:12
  • You could write your own extension method, and then have `string FN = viewModel.FirstName.OrNA();` – Blorgbeard Nov 15 '17 at 21:13
  • @Skullomania Do you want to check for empty string as well as null or just null? I had thought just null because that is what you said. – Blake Thingstad Nov 15 '17 at 21:16
  • I am trying to check for null or empty – Skullomania Nov 15 '17 at 21:17
  • one more option C# null-coalescing operator: string FN = viewModel.FirstName ?? "N/A"; – MRsa Nov 15 '17 at 21:19
  • @Kirk If you have an additional solution to the canonical version of the question then *post that answer to the canonical*, rather than to duplicates of it. – Servy Nov 15 '17 at 21:26
  • @Kirk You said that the question needs another solution. I'm simply saying that if you think that's the case, it should be posted to the canonical version not here. – Servy Nov 15 '17 at 21:31

2 Answers2

1

Create an extension method as such:

static class Helper
{
       public static string NotApplicableIfNullOrEmpty(this string str) => String.IsNullOrEmpty(str) ? "N/A" : str;
}

then do something like:

string firstName = viewModel.FirstName.NotApplicableIfNullOrEmpty();
string lastName = viewModel.LastName.NotApplicableIfNullOrEmpty();
string address = viewModel.Address.NotApplicableIfNullOrEmpty();
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
0

First and simplest way is: using ternary operator

string fristName = String.IsNullOrEmpty(viewModel.FirstName) ? "N/A" : viewModel.FirstName;

Another option is using custom model binder: ASP.NET Model Binder

Ashutosh Singh
  • 609
  • 6
  • 21