Developer forum

Forum » Templates » Avoid templates from "breaking" if resource isn´t found

Avoid templates from "breaking" if resource isn´t found

Hans Ravnsfjall
Hans Ravnsfjall
Reply

Hi

On a razor page template, I call on an external Item called "Alert", and the item-id is 1. It´s based on this https://doc.dynamicweb.com/api/html/c288eaa6-2bb8-405c-d939-112efc1ff104.htm

 

@{
 
  string myint="1";
  var item = Dynamicweb.Content.Items.ItemManager.Storage.GetById("Alert", @myint);
  var alertstate = item["AlertState"].ToString();
  var takeover = item["Takeover"].ToString();
  var alerttext = item["Text"].ToString();
  var timespan = item["Timespan"].ToString();
 }
 

Now, this requires that the Item Id = 1 exists. If someone accidentially deletes the page where itemid 1 is located, the Item reference no longer exists, and the whole website breaks down because of this. How can I check if the item of this specific type and id exists, before I do the processing?

 

/Hans


Replies

 
Imar Spaanjaars Dynamicweb Employee
Imar Spaanjaars
Reply
This post has been marked as an answer

Check if item isn't null?

if (item != null)

{

// Your code here

}

Votes for this answer: 1
 
Mario Santos Dynamicweb Employee
Mario Santos
Reply
This post has been marked as an answer

Hi Hans,

 

You can check if the item returned by GetById is null by simply doing: item != null.

For the other variables you may want to check if the field exists and for that you can do: (item["AlertState"] ?? "").ToString()

 

BR, Mario

Votes for this answer: 1
 
Nicolai Pedersen
Reply
This post has been marked as an answer

Add a null reference check like this:

@{
  string myint="1";
  var item = Dynamicweb.Content.Items.ItemManager.Storage.GetById("Alert", @myint);
  if(item != null){
    var alertstate = item["AlertState"].ToString();
    var takeover = item["Takeover"].ToString();
    var alerttext = item["Text"].ToString();
    var timespan = item["Timespan"].ToString();
  }else{
    var alertstate = "Alert default"
    var takeover = "Alert default"
    var alerttext = "Alert default"
    var timespan = "Alert default"
  }
}
Votes for this answer: 1
 
Nicolai Pedersen
Reply

Lol!

 
Hans Ravnsfjall
Hans Ravnsfjall
Reply

Thanx for the help and the fast response.

 

Very simple indeed 👍🏻 

 

 
Nicolai Pedersen
Reply

You better do like this:

@{
  var alertstate = "Alert default"
  var takeover = "Alert default"
  var alerttext = "Alert default"
  var timespan = "Alert default"

  string myint="1";
  var item = Dynamicweb.Content.Items.ItemManager.Storage.GetById("Alert", @myint);
  if(item != null){
    alertstate = item["AlertState"].ToString();
    takeover = item["Takeover"].ToString();
    alerttext = item["Text"].ToString();
    timespan = item["Timespan"].ToString();
  }
}

 

You must be logged in to post in the forum