Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.Net MVC2 RenderAction changes page mime type?

It appears that calling Html.RenderAction in Asp.Net MVC2 apps can alter the mime type of the page if the child action's type is different than the parent action's.

The code below (testing in MVC2 RTM), which seems sensible to me, will return a result of type application/json when calling Home/Index. Instead of dispylaying the page, the browser will barf and ask you if you want to download it.

My question: Am I missing something? Is this a bug? If so, what's the best workaround?

controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        ViewData[ "Message" ] = "Welcome to ASP.NET MVC!";

        return View();
    }

    [ChildActionOnly]
    public JsonResult States()
    {
        string[] states = new[] { "AK", "AL", "AR", "AZ", };

        return Json(states, JsonRequestBehavior.AllowGet);
    }
}

view:

<h2><%= Html.Encode(ViewData["Message"]) %></h2>
<p>
    To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>.
</p>
<script>
  var states = <% Html.RenderAction("States"); %>;
</script>
like image 627
Gabe Moothart Avatar asked Mar 15 '10 15:03

Gabe Moothart


1 Answers

I Consider this a bug. If this is a child action being rendered, why it would change the parent action response? The same happens with Html.Action, which renders it into a string. My workaround is doing:

Html.ViewContext.HttpContext.Response.ContentType = "text/html";

after calling Html.Action. I suppose someone could write a wrapper Html Helper extension, something like:

var aux = Html.ViewContext.HttpContext.Response.ContentType;
Html.Action(....); // or Html.RenderAction(...)
Html.ViewContext.HttpContext.Response.ContentType = aux;
like image 162
niv Avatar answered Oct 14 '22 08:10

niv