0

I have an MVC application and I would like to pass an html table from the controller to the view using json.

I found this Q&A in this site: Sending HTML Code Through JSON which recommends json_encode but it's for PHP and I'm using C#...

How can I pass an HTML Table using Json?

Currently I tried:

return Json(MyHTMLTable);

In my view:

<script type="text/javascript">
$(document).ready(function () {
    $.ajax({
        url: '@Url.Action("GetTable","MyPages")',
        type: 'POST',
        success: function (result) { $('#ph').html(result.responseText); },
        error: function (result) {
            $('#err').html(result.responseText);
        }
    })
});

(ph is a div)

I got the following error: A circular reference was detected while serializing an object of type 'System.Web.UI.WebControls.TableRow'.

Community
  • 1
  • 1
DA_Prog
  • 243
  • 3
  • 7
  • 13

2 Answers2

1

Change your ajax to remove the @URL.Action

$.ajax({
    url: 'MyPages/GetTable',
    type: 'POST',
    success: function (result) { $('#ph').html(result.responseText); },
    error: function (result) {
        $('#err').html(result.responseText);
    }
})

in your ActionResult() return a PartialView()?

In your partial view named TableHtml in this example will be your html

public ActionResult GetTable(){

     // do something

     return PartialView("TableHtml");


}

Ajax will accept this

However if you must return HTML then you can wrap in a Json

public ActionResult GetTable(){

     // do something
     String myHtml = "<div></div>;

    return Json(myHtml, JsonRequestBehaviour.AllowGet);
}
CR41G14
  • 5,124
  • 5
  • 39
  • 61
  • It's not a partial view. I generate the html table dynamically, so I can't tell how the view might look like.... – DA_Prog Dec 06 '12 at 13:16
1

First of all, there is no need to pass an HTML table from a controller to a view using JSON. JSON is meant as a way to transmit stringified data, usually between web services and clients. It is similar in function to SOAP. Transmitting data from your controller to your view in this manner is bad because you lose the strongly-typing that passing with a model affords you.

So, what you can do is simply pass your HTML table as a variable to your view in a view model. You could also use ViewBag, but you lose strong typing this way. Either way, assuming that the table is generated in your C#, you simply need to convert the string containing the HTML to a MvcHtmlString. You do it like this:

var table = MvcHtmlString.Create("<table>...");

and then either include this in your model or in the ViewBag. You can then on your view page use classic Razor syntax to print the table to the page:

@Model.Table

or

@ViewBag.table
Levi Botelho
  • 22,763
  • 5
  • 51
  • 94