In sql server I create views where I can check for null values and replace them with a default if I want (i.e. ISNULL(PrimaryPhone, 'No Primary #') AS PrimaryPhone. I used a lot of views in my asp.net web forms application, but I am now learning MVC 4 and want to start out right.
I have a model, controller and view set up for my client table. I would like to be able to replace null/empty values with ("Not Entered") or something like that. I believe this needs to go in the controller, please correct me if I'm wrong.
I saw an example that uses hasvalue, but it is not available through intellisense.
How would I replace empty/null values without using DefaultValue in my model?
Thanks
var result = db.Clients.Select(x => new
{
CustomerID = x.CustomerID,
UserID = x.UserID,
FullName = x.FullName,
EmailAdd = x.emailadd.DefaultIfEmpty("No Email"),....
You can use the ?? operator to set a default value when something is null:
var result = db.Clients.Select(x => new
{
CustomerID = x.CustomerID,
UserID = x.UserID,
FullName = x.FullName,
EmailAdd = x.emailadd ?? "No Email", ...
If you need more control, for example checking for both null and empty, you can also use the ?: operator (also known as the "conditional operator" or "ternary operator"):
var result = db.Clients.Select(x => new
{
CustomerID = x.CustomerID,
UserID = x.UserID,
FullName = x.FullName,
EmailAdd = string.IsNullOrEmpty(x.emailadd) ? "No Email" : x.emailadd, ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With