Question

I'm using a web service to get and render a GridView to HTML. The idea is to generate it asynchronously (to generate the data in a hidden row for an expandable grid, for example).

[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public static string ExpandRowService(string contextKey)
{
    try
    {
        long recId = long.Parse(contextKey);
        return RenderControlToHtml("/Controls/SubGrid.ascx", recId);
    }
    catch (Exception)
    {
        return "";
    }
}

public static string RenderControlToHtml(string controlPath, params object[] constructorParams)
{
    var page = new Page
    {
        EnableEventValidation = false,
        EnableViewState = false,
    };
    var form = new HtmlForm
    {
        EnableViewState = false
    };
    page.Controls.Add(form);

    var control = page.LoadControl(controlPath, constructorParams);
    form.Controls.Add(control);

    return page.RenderControl();
}

The problem is that rendering to HTML like that needs a dummy form to render into, and that dummy form has a __VIEWSTATE hidden input:

<form method="post" action="ExpandRowService" id="ctl00">
<div class="aspNetHidden">
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="" />
</div>

On postback after any other action, there are more than one __VIEWSTATE variables and that's obviously a no-no.

How can I force rendering of a control to HTML without the accursed __VIEWSTATE hiden input?

EDIT:

I'm using a GridView and not making a table from scratch because I need its data binding capabilities to set various styles (for example: mark negative amounts in red).

Was it helpful?

Solution 2

It appears that it is not possible to generate the control with LoadControl into a form (required) and not have a __VIEWSTATE.

I made my own TableWriter, and did some rowbinding to it. Best I could do.

OTHER TIPS

You can render the control itself, without the surrounding form. All you need is to setup a HtmlTextWriter instance backed by a reasonable storage, such as a StringBuilder:

// create control and make it part of a form and page
…

// render just the control
var c = new StringBuilder();
using (var sw = new StringWriter(c))
{
    using (var writer = new HtmlTextWriter(sw))
    {
        control.RenderControl(writer);
    }
}
return c.ToString();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top