0

Data is a string representing youtube embedded code and is read from my database. An example of such string is:

<iframe width="425" height="349" src="http://www.youtube.com/embed/Ki5GNq_3qT8" frameborder="0" allowfullscreen></iframe>

In my controller code I have something like below:

// the parameter embed contains the youtube code
public ActionResult Index(string embed)
{
    ViewBag.Embed = embed;
    return View();
}

My question is how do I write the Razor code that will inject the embedded HTML code into my view?

3 Answers 3

1

You need to render as a HTML string. Try this in your view:

<body>
    @(new HtmlString((String)ViewBag.Embed))
</body>

Hope this helps :)

EDIT

If you're trying to render the entire string go with this, if it's just part of it then the answer by ek_ny is the way to go.

Sign up to request clarification or add additional context in comments.

5 Comments

Yes, I'm trying to render the whole string. But your solution didn't work. Am missing something?
Try @Html.Raw((String)ViewBag.Embed). If that works Ill update the answer.
No error. But the flash player didn't appear as would be expected. If I write the youtube code straight up into the view it works.
It didn't work. Below is the view code, please let me know if I'm doing anything stupid. @{ ViewBag.Title = "Testing"; } @Html.Raw((String)ViewBag.Embed)
Looks like your workflow is off. Are you actually getting the string? Put a debug line in your controller when you assign "Embed" and make sure you actually have the value.
0
<iframe width="425" height="349" src="http://www.youtube.com/embed/@ViewBag.Embed" frameborder="0" allowfullscreen></iframe>

You might want to also make sure the code is html encoded.

1 Comment

Pleae clarify, I am fairly new to ASP.NET-MVC. If I write the code straight up into my view it works perfectly. But I need it to be dynamic because the data is coming from my database.
0

Try razor syntax:

@: @ViewBag.Embed

Or

@Html.Raw(ViewBag.Embed)

Comments

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.