Search code examples
c#asp.net-mvcrazor

How to set the content type?


I'm trying to change one of my razor MVC5 views to produce a plain text instead of html. I put this:

@{
    this.Response.ClearContent();
    this.Response.ContentType = "text/plain";
}

in my cshtml file but it's still producing an html. I also tried setting it in the controller:

[AcceptVerbs("GET", "POST", "PUT", "DELETE")]
public ActionResult Version()
{
    Response.ContentType = "text/plain";
    ViewData["ver"] = "v1.1";
    return View();
}

Still does not work.

Any ideas?


Solution

  • You need to render your view into a string and send it a string from your action method. Here's how you can render a view to string (taken from this answer):

    public string RenderRazorViewToString(string viewName, object model)
    {
        ViewData.Model = model;
        using (var sw = new StringWriter())
        {
            var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
            var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
            viewResult.View.Render(viewContext, sw);
            return sw.GetStringBuilder().ToString();
        }
    }
    

    When you will get a rendered string, just do return Content(renderedString) in your action:

    public ActionResult Version()
    {        
        ViewData["ver"] = "v1.1";
        var renderedString = RenderRazorViewToString("Version", null);
        return Content(renderedString);
    }