DA_Prog
DA_Prog

Reputation: 283

Passing HTML Table to MVC View from controller

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

Upvotes: 0

Views: 4259

Answers (2)

CR41G14
CR41G14

Reputation: 5594

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);
}

Upvotes: 1

Levi Botelho
Levi Botelho

Reputation: 25214

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

Upvotes: 1

Related Questions