简体   繁体   中英

Optimal way to use if-statement in MVC View

I'm doing a summer internship as a web developer and this friday I had a problem I wasn't sure exactly which way was the "best" way to solve. I don't have the code here, but as it's not a code/syntax problem, but more of a "how do I go about this"-problem.

Basically, I have a model with a Customer class which I, in my controller, assign values from the database. So in my CustomerController I have a LINQ query which grabs values from the database and assigns these values to the corresponding variables in the Customer Model. Then, in my CustomerView, I show these variables in a table for each Customer. So I have a loop that basically says:

foreach (item in Model) 
<td>@item.Name</td>
<td>@item.Age</td>
<td>selfmadeDecryptFunction(@item.Email)</td>

and so on. Thing is, another developer has written a crypt/decrypt function which doesn't work if the value is NULL or 0. Sometimes, the @item.Email is empty which because of this decryption results in an error. Because of this, I want to just print the string NULL when @item.Email is null, and not run the decrypt function.

What is the "best" way to go about this? Do I write inline javascript if-else? Is there something I can do in the LINQ query or in the CustomerController? What's the "correct" way? I don't really want to go ask my coworkers about this because it's quite basic, and I could fix this myself, but I want to know what the correct way to solve this problem is.

As you said:

Because of this, I want to just print the string NULL when @item.Email is null, and not run the decrypt function.

You can simply apply an if construct to solve that:

    foreach (item in Model)
    { 
      <td>@item.Name</td>
      <td>@item.Age</td>
      @if(item.Email!=null)
      {
       <td>item.Email</td>
      }
      else
      {
        <td>NULL</td>
      }
   }

In the code above if @item.Email is not null then it will be as it is (real value from Model), and if it is null then NULL will be printed on a place where should be @item.Email written.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM