0

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?

tereško
  • 58,060
  • 25
  • 98
  • 150
max
  • 9,708
  • 15
  • 89
  • 144
  • Could you return a `ContentResult` instead of the generic `ActionResult`? http://msdn.microsoft.com/en-us/library/system.web.mvc.contentresult(v=vs.118).aspx – Paul Abbott Dec 15 '14 at 21:47

1 Answers1

3

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);
}
Community
  • 1
  • 1
Vsevolod Goloviznin
  • 12,074
  • 1
  • 49
  • 50