asp.net - MVC ViewModel Custom Property not populating if null exists -


i have simple viewmodel, based on customer domain model.

i'm adding 1 property it: customernameaddress made of customername, contact , town of domain model.

however, if of customername, contact or town null - customernameaddress null.

is there anyway of checking null within query below, , changing "", viewmodel works correctly?

i had tried:

customernameaddress = (p.customername || "") + ", " + (p.contact || "") + ", " + (p.town || "") 

... vs advised operator '||' cannot applied operands of type 'string' , 'string'

my controller code below.

thank you,

mark

    public jsonresult lookup(string id)     {         string username = null;      if (httpcontext.user.identity.isauthenticated)     {         username = httpcontext.user.identity.name;     }      var customers = p in db.customers                     p.username.equals(username)                     select new customerlookupviewmodel                     {                         customerid = p.customerid,                         email = p.email,                         customernameaddress = p.customername + ", " + p.contact + ", " + p.town                     };          return json(customers, jsonrequestbehavior.allowget);     } 

update

i amended code to:

ss

but error on p.contact (underlined above) advising: cannot implicitly convert type 'string' 'bool'

however, viewmodel has contact string:

 public class customerlookupviewmodel {     public string customernameaddress { get; set; }     public int customerid { get; set; }     [required]     [display(name = "customer name")]     public string customername { get; set; }     [display(name = "customer contact")]     public string contact { get; set; } 

2nd update - working

i updated conditions enclosed in brackets, , it's working:

customernameaddress = ((p.customername == null) ? "" : (p.customername + ", ")) +                         ((p.contact == null) ? "" : (p.contact + ", ")) +                         ((p.town == null) ? "" : (p.town)) 

you can use condition operator ? :

 customernameaddress = (p.customername == null || p.contact == null || p.town == null ) ? "" : p.customername + ", " + p.contact + ", " + p.town 

query be.

var customers = p in db.customers                 p.username.equals(username)                 select new customerlookupviewmodel                 {                     customerid = p.customerid,                     email = p.email,                     customernameaddress =  (p.customername == null || p.contact == null ||  p.town == null ) ? "" : p.customername + ", " + p.contact + ", " + p.town                  }; 

Comments