Search code examples
c#tagsasp.net-mvc-5innerhtmlasp.net-mvc-views

How can I get a tag in a view and set some InnerHtml to this tag?


I am coding a MVC 5 View, and I would like to set the InnerHtml of an HTML element.

Here is the HTML code that I would like to add some additional HTML to:

<section id="mainContentArea" class="content">
    <!-- Your Page Content Here -->
</section>

As a test, I would like to add the following HTML to the above section:

<p>Test data</p>

So the resulting HTML will be:

<section id="mainContentArea" class="content">
    <!-- Your Page Content Here -->
    <p>Test data</p>
</section>

This is the code I have coded:

@{
    var tag = new TagBuilder("mainContentArea");
    tag.InnerHtml += "<p>Test data</p>";
}

The above code does not add any HTML code to the section.

May I please have some help with this?

Thanks in advance.


Solution

  • You can use JQuery to add html dynamically.

    $("#mainContentArea").html("<p>Test data</p>");
    

    However if you have your html is in variable then you can use @Html.Raw method.

    @{string html="<p>Test data</p>";}
       <section id="mainContentArea" class="content">
           @Html.Raw(html)
       </section>