Home > Net >  How can I render two variables in src attribute of razor view?
How can I render two variables in src attribute of razor view?

Time:08-08

The framework I am using is .NET 6.

Previously, the src attribute of the image element like this:

<img src="@ImageServer/images/BG.png" />

The variable of ImageServer stores the URL of the image server.

Recently, I need to add a token in it for anti-theft chain.

I tried it like this:

<img src="@ImageServer/images/BG.png@GetToken()" />

However, after the program is run, the src turns out to be this:

<img src="https://www.aaa.com/images/BG.png@GetToken()" />

What's wrong with my code and how can I render two variables in src attribute? Thank you.

CodePudding user response:

The text just before the @ is causing the render engine to not parse the @ as a server-side code indicator.

Make the whole value server-side calculated, instead of outputting small pieces of server-side values into client-side values. For example:

<img src="@(ImageServer   "/images/BG.png"   GetToken())" />

This way the view engine sees everything within the @() as a server-side expression and outputs the result of that expression.

Similarly, with string interpolation:

<img src="@($"{ImageServer}/images/BG.png{GetToken()}")" />
  • Related