1

I'm trying to concat a string in MVC

This is what I'm trying to do

<img src="~/Content/CompanyLogo/@Html.DisplayFor(modelItem => item.CompanyLogo)+".jpg"" />

But it isn't allowed...

What should I be doing? I am the designer and I don't have the option to edit the model to provide it in the correct format...

2 Answers 2

1

Try this

<img src="~/Content/CompanyLogo/@(Model.CompanyLogo).jpg" />

Assuming CompanyLogo is a property of your model,Razor will render the value of your CompanyLogo property when the view is rendered.

Note that i used @() syntax. The parenthesis syntax explicitly tells razor that it is an expression to be evaluated.

Here is a handy list of razor syntax reference, written by Phil

If it is in a for each loop, try this

@foreach (var img in Model.Images)
{
  <img src="@Url.Content("~/Content/CompanyLogo/"+img.CompanyLogo+".jpg")"/>
}

or a more simplified version (~ works from ASP.NET MVC4 onwards only)

@foreach (var img in Model.Images)
{
  <img src="~/Content/CompanyLogo/@(img.CompanyLogo).jpg""/>
}
Sign up to request clarification or add additional context in comments.

1 Comment

It won't accept @ Model, only @item as it's part of a foreach loop. using @ item.CompanyLogo.jpg produces a compiler error
1

You don't need DisplayFor in this case. Try this (assuming your CompanyLogo is a string property directly on the model):

<img src="~/Content/CompanyLogo/" + @Model.CompanyLogo + ".jpg" />

2 Comments

It renders it verbatum
Sorry, I can't +1 with my rep

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.