alpha
alpha

Reputation: 501

Rendering an html string to view

I have two controller actions that target the same view. That is, I have specified a view name on the call to View from controller action. The second action puts an html string in a ViewBag. I simply just want to display this html string in the view. I have tried

@ViewBag.HtmlDoc

and

@Html.Raw(ViewBag.HtmlDoc)

but nothing is rendered.

Any help would be appreciated. Thanks in advance.

--controller code---

public ActionResult ShowReport(string URL)
        {
            string tableString = ""; 

            [Code to Create table called ReportTable and add rows etc]

            tableString = RenderControlToString(ReportTable );

            ViewBag.Table= tableString; 

            return View("ShowReport");

        }

I debugged the ViewBag.Table on the View and can see the html string. But the View never gets updated / rendered. I tested with a simple text like:

@if (ViewBag.Table != null)
{
        //@ViewBag.Table;       
        @:The day is: @DateTime.Now.DayOfWeek.
}

It goes into the code so I know ViewBag.Table is not null, but the string doesn't get rendered, either.

Do I need to refresh RenderBody() in the _layout.cshtml??? or something to that effect?

-- ajax call--

a button onclick event calls this ajax method:

$.ajax({

            url: "/Home/ShowReport",
            data:  { URL: urlString} ,
            type: 'POST',
            success: function(data) {
               alert(data);
            },
            error: function (e, textStatus, jqXHR) {
                alert(e.statusText);

            }

        });

Upvotes: 1

Views: 731

Answers (1)

Dave Alperovich
Dave Alperovich

Reputation: 32490

Change your action method to return JSON content

public ActionResult ShowReport(string URL)
    {
        string tableString = ""; 

        [Code to Create table called ReportTable and add rows etc]

        tableString = RenderControlToString(ReportTable );

        //ViewBag.Table= tableString; 

        return this.Content(tableString, "application/json");

    }

alter your JQuery to reutilize your return value

        success: function(data) {
           $('#divTable').innerHTML(data);

and add a div to your view where you want to render the html

<div id='divTable'></div>

Upvotes: 1

Related Questions