3

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.

Simon
  • 7,991
  • 21
  • 83
  • 163
  • `TagBuilder` is used for generating a html element (e.g. `div` or `input` etc), not for getting an element. If your wanting to dynamically add content, you need javascript/jquery –  May 27 '15 at 10:28
  • _Why_ do you want to do this? This is not how MVC is supposed to be used. Can't you just include a partial there, or render a `@variable` containing the HTML string you want to print? – CodeCaster May 27 '15 at 10:34
  • The jQuery answer is great! did you want to use jQuery or C#? Did you want to pass data from the Action to the view? – shammelburg May 27 '15 at 10:35

1 Answers1

1

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>
Manish Parakhiya
  • 3,732
  • 3
  • 22
  • 25