开发者

Executing dynamic HTML from a string variable in C#

开发者 https://www.devze.com 2023-03-23 04:48 出处:网络
Data is a string representing youtube embedded code and is read from my database. An example of such string is:

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 cod开发者_开发知识库e 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?


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.


<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.


Try razor syntax:

@: @ViewBag.Embed

Or

@Html.Raw(ViewBag.Embed)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号