Good day, I'm try to use action links with Url.Action
inside @Html.Raw
in my ASP.NET MVC3 project. Everything works fine without @Html.Raw
, but with it images can't display on the page, I'm try to use Html.Encode
inside Raw, but then it's show me the naked HTML on the page.
@Html.Raw(<a href="@Url.Action("ActionName", "Controller", new {id = 1})" target="_blank">
<img src="@Url.Content("~/Content/Images/simpleImage.png")"/>
</a>)
Any ideas why it's not render right code?Also when I hover over the place with image it pop up for me next code: sitename.com/Controller/@Url.Action(
I'm try to shielding the " it's not help
Edit
This action link is a part of query from database, which I display like next:
@Html.Raw(model.FieldWithHtmlCharactersInDatabase)
You need to pass string, try this
@Html.Raw("<a href='" + @Url.Action("ActionName", "Controller", new {id = 1})' " + target='_blank'>
<img src='" + @Url.Content("~/Content/Images/simpleImage.png") " + "/>
</a>")
Try this instead where you are passing in the string variable and escaping the "
correctly.
@Html.Raw("<a href=\"" +
Url.Action("ActionName", "Controller", new {id = 1})
+ "\" target=\"_blank\"><img src=\"" +
Url.Content("~/Content/Images/simpleImage.png") + "\"/></a>")
However I do not understand why you want this in @Html.Raw
when this will give you the same output;
<a href="@Url.Action("ActionName", "Controller", new {id = 1})" target="_blank">
<img src="@Url.Content("~/Content/Images/simpleImage.png")" />
</a>
Update
After you have updated your question, you are attempting to Execute Razor code from DB strings. I would suggest that you take a look at some of these questions on StackOverFlow;
ASP.net MVC: Execute Razor from DB String?
Pulling a View from a database rather than a file
Please note that your original question is very different from what you want.
The following code:
<img src="@Url.Action("ActionName", "Controller", new {id = 1, width=100, height=100})" alt="" />
will yield this output:
<img src="Controller/ActionName/1?width=100&height=100" alt="" />
You will get the same surrounding Action helper with Raw:
<img src="@Html.Raw(Url.Action("ActionName", "Controller", new {id = 1, width=100, height=100}))" alt="" />
So this must be a bug in Razor/MVC. One (tedious and ugly) workaround I found is this:
@Html.Raw("<img src=\"" + Url.Action("ActionName", "Controller", new {id = 1, width=100, height=100}) + "\" alt=\"\" />" )
Hopefully Microsoft will fix this.
If someone has the same problem in the future, for me it worked to remove the ~ infront of the image string!