7

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"),....
4

1 に答える 1

9

??を使用できます。何かが null の場合にデフォルト値を設定する演算子:

var result = db.Clients.Select(x => new
        {
            CustomerID = x.CustomerID,
            UserID = x.UserID,
            FullName = x.FullName,
            EmailAdd = x.emailadd ?? "No Email", ...

null と空の両方をチェックするなど、さらに制御が必要な場合は、?: 演算子(「条件演算子」または「三項演算子」とも呼ばれます) を使用することもできます。

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, ...
于 2012-12-15T19:08:18.710 に答える