user320587
user320587

Reputation: 1367

Render DIV tag inside table using ASP .net MVC HTML helpers

I am trying to render some DIV inside a table td tag using HTML Helper methods in ASP .net MVC. For some reason, the divs are not being rendered. here is my sample code. My Model has two properties ID and a list of Strings. The strings are basically HTML DIV tags.

<table>
<tr>
 <th>ID</th>
 <th>Schedule</th>
</tr>
<% foreach (var item in Model) { %>
  <tr>
    <td><%: Html.DisplayFor(modelItem => item.ID) %></td>
    <td>
       <% foreach (var bar in item.Details)
        {
           Html.DisplayFor(modelItem => bar);
        }       
        %>
    </td>
   </tr>
 <% } %>
</table>

The view is populated with the ID but not the DIV tags. Can someone point to me what I could be doing wrong.

Thanks, Javid

Upvotes: 1

Views: 2423

Answers (2)

Code Monkey
Code Monkey

Reputation: 643

You could use jQuery's .getJSON in conjunction with the .html method to spit out HTML markup which contains the DIV:

   <script>
        $(document).ready(
                        function () {
                            $("#Button2").click(
                                    function () {
                                        $("#ohyeah").html("blah blah blah");
                                        var jsonlisteningobject = {};
                                        $.getJSON("/home/somefoo", null, function (data) {
                                            var div = $('#ohyeah');
                                            div.html("<td>" + data.someNumber + "</td><td>" + data.someString1 + "</td><td>" + data.someString2 + "</td><td>" + data.someListofStrings[3] + "</td>");
                                        }
                                            );
                                        $.getJSON("/home/someHTML", null, function (data) {
                                            $("#someHTMLstuff").html(data);

                                        });
                                    }
                                );

        });
    </script>

'someHTMLstuff' and 'ohyeah' can be DIV elements on your page.

Upvotes: 0

nemesv
nemesv

Reputation: 139758

You are missing the <%: %> around the Html.DisplayFor

<td>
   <% foreach (var bar in item.Details) { %>
       <%: Html.DisplayFor(modelItem => bar) %>
   <% } %>
</td>

because the Html.DisplayFor doesn't write directly to the Response just returns the rendered template as a MvcHtmlString, so it's need to be "outputted" with the <%: %>.

Upvotes: 1

Related Questions