Travis Heeter
Travis Heeter

Reputation: 14084

How to end code inside a string?

I know this is basic, but I'm feeling there's got to be a better way to do this.

I have a dynamic file name:

/img/car-1.jpg
/img/car-2.jpg
/img/car-3.jpg

In my Model View, I want to do this:

<img src="/img/[email protected]" />

Unfortunately the compiler considers the .jpg to be part of the code, and says 'int' does not contain a definition for jpg.

I also tried this:

<img src="/img/car-@{Model.Number}.jpg" />

But it gives me this error: 'System.Web.Mvc.WebViewPafe<TModel>.Model' is a 'property' but is used like a 'type'.

So for now I use a string builder at the top of the page, but it seems so verbose for such a simple issue. How can I tell C# "I'm done with this @ code section?"

Edit: a suggestion said my question was like this one, so here's how it's different: I am using the solution to that question in my code example, and still getting an error.

Upvotes: 2

Views: 101

Answers (2)

Christian Phillips
Christian Phillips

Reputation: 18769

try parenthesis ( )

<img src="/img/car-@(Model.Number).jpg" />

Take a look here C# Razor Syntax Quick Reference

Upvotes: 7

Martin Noreke
Martin Noreke

Reputation: 4146

Try using a String.Format as your source:

 <img src="@String.Format("/img/car-{0}.jpg", Model.Number)" />

Upvotes: 4

Related Questions