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

£可爱£侵袭症+ 提交于 2019-12-05 09:47:30

问题


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?


回答1:


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

Solution:

public ActionResult ControlsLangJsFile()
    {
        Response.ContentType = "text/javascript";
        return View("~/Views/Dictionary/ControlsLangJsFile.ascx");
    }



回答2:


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...



回答3:


Like this, just change the content type accordingly:

ASP.NET MVC and text/xml content type




回答4:


Try:

return Json(new
{
      uCode = SysContext.CurrentUserCode,
      uPwd = SysContext.CurrentUserPwd,
      rMe = SysContext.RememberMe
}, "application/json", JsonRequestBehavior.AllowGet);


来源:https://stackoverflow.com/questions/4439355/how-to-change-returned-contenttype-in-asp-net-mvc-controller-actionresult

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!