Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change returned ContentType in ASP.NET MVC controller (ActionResult)

Tags:

I have ASP.NET MVC controller named dictionary with method ControlsLangJsFile. Method returns view of users control (ASCX) which contain JavaScript variables.

When i call the method it returns variables with parsed strings, but Content Type is html/text. It should be: application/x-javascript

public ActionResult ControlsLangJsFile()     {         return View("~/Views/Dictionary/ControlsLangJsFile.ascx",);     } 

How do i achieve this?

like image 879
jmav Avatar asked Dec 14 '10 12:12

jmav


2 Answers

Users control doesn't accept ContentType="text/xml"

Solution:

public ActionResult ControlsLangJsFile()     {         Response.ContentType = "text/javascript";         return View("~/Views/Dictionary/ControlsLangJsFile.ascx");     } 
like image 157
jmav Avatar answered Sep 24 '22 12:09

jmav


I had this same question while building a razor view with JS in it and attempted to use @jmav's solution:

public ActionResult Paths() {     Response.ContentType = "text/javascript"; //this has no effect     return View(); } 

That doesn't work when you are returning a View(). It seems that the view rendering sets the content type itself despite what is assigned in the controller method.

Instead, make the assignment in the view code itself:

// this lives in viewname.cshtml/vbhtml @{     this.Response.ContentType = "text/javascript"; } // script stuff... 
like image 28
Peter Avatar answered Sep 26 '22 12:09

Peter