0

I have an entry in Razor View which is

<li data-img-url="@stock["images"][0]["url"]">
@* stock is a JObject which can contain or cannot contain ["images"]*@

Irrespective of location of null occurence, how to get the final string data-img-url="". Also how to handle such situations where output of statement is needed without adding extra code blocks such as If/Else or Try/Catch

Flood Gravemind
  • 3,773
  • 12
  • 47
  • 79

4 Answers4

2

JObject has a SelectToken method which you can utilize for your scenario.

  JObject jsonDoc = JObject.Parse(json);

  Console.WriteLine(jsonDoc.SelectToken("images[0].url"));

Here you will find reference code for SelectToken

SelectToken will return empty if no token found and return results if its a valid result

Vishal Sharma
  • 2,773
  • 2
  • 24
  • 36
1

In just C#, the null-propagating operator can help here, i.e.

var x = obj?["bar"];

note however that this only deals with nulls; it won't help you if the problem is a KeyNotFoundException (because obj isn't null, but there's no key "bar"). So: in the general case: just write a method that does what you need, and which also makes everything cleaner; this could be an extension method on whatever stock is, noting that extension methods do not null check on the this argument:

public static string GetFrob(this Stock stock, string grapple, int foo, string blap)
{...}

...

<li data-img-url="@stock.GetFrob("images", 0, "url")">
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
0

I do not know if I have understood the question well, but according to what you want to do you have to put an if:

@(stock["images"][0]["url"] == null ? "" : stock["images"][0]["url"])

it is an if, but with linear syntax

Ahmed Msaouri
  • 316
  • 1
  • 10
0

Use a ternary:

<li data-img-url="@(stock["images"][0]["url"]! = null:stock["images"][0]["url"]:"""> @* stock is a JObject which can contain or cannot contain ["images"]*@

If the doesn't work, encase the entire attribute in the ternary.