views:

31

answers:

1

Hi,

I am building a simple CMS with asp.net MVC and I have almost all the parts working. I have one minor issue which I can't work out how to solve. I have a Html helper method that renders the content of area. This method however uses the Response.Write to write its content rather than returning a string. The reason for this is that I'm performing a partial request and hence do not have a string to return.

My template body looks like this:

<body>
    <h1>Default Template</h1>
    <% Html.ContentArea("Main"); %>
</body>

The problem I'm having is that the content renders above the H1 tag. My understand was that the h1 should already be in the response and my call to response.Write() would therefore append content after that point. This is obviously not happening. What am I missing here.

I've used partial requests before and they always render in the correct place. I haven't yet used them with MVC 2, this could possibly be the problem.

Below is the content area extension method. The widget render method varies and is where the partial request occurs. However even the start and end container tag render above h1 so it has to be something fundamental I'm doing wrong.

    public static void ContentArea(this HtmlHelper htmlHelper, string areaName)
    {
        var container = new TagBuilder("div");
        container.GenerateId(areaName);
        container.AddCssClass("content-area");

        var response = htmlHelper.ViewContext.HttpContext.Response;

        response.Write(container.ToString(TagRenderMode.StartTag));

        var pageWidgets = htmlHelper.ViewData[areaName] as IList<PageWidget>;
        if (pageWidgets != null)
            foreach (var widget in pageWidgets)
            {
                widget.GetInstance().Render(new WidgetContext(htmlHelper.ViewContext, widget));
            }

        response.Write(container.ToString(TagRenderMode.EndTag));
    }

It's probably something simple... Isn't it always :)

EDIT:

Even the below doesn't render correctly taking previous comments to use ViewContext.Writer instead makes no difference.

    public static void ContentArea(this HtmlHelper htmlHelper, string areaName)
    {
        var container = new TagBuilder("div");
        container.GenerateId(areaName);
        container.AddCssClass("content-area");

        var writer = htmlHelper.ViewContext.Writer;

        writer.Write(container.ToString(TagRenderMode.StartTag));

        writer.Write(container.ToString(TagRenderMode.EndTag));
    }

This renders as

<div id="Main" class="content-area"></div>
<h1>Default Template</h1>

Thanks,

Ian

+1  A: 

Have you tried using ViewContext.Writer.Write rather than Response.Write? I think that's what I use in my extension methods, and I haven't had any issues.

Jeff Sheldon
I have tried both, they produce exactly the same output. I've included a simplified method that also produces the same result.
madcapnmckay