I've got the following controller:
public class HelloController
{
public ActionResult Index()
{
return View()
}
public ActionResult Hello()
{
return Json(new{ greeting = "hello, world!" }, JsonRequestBehavior.AllowGet);
}
}
Then, inside Index.cshtml
:
...html stuffs
<script type="text/javascript">
alert("@Html.Action("Hello")");
</script>
What I'm finding is that, when going to this url in my browser, the response content type is application/json; charset=utf-8
which causes the browser to render the html as a string instead of as... a web page.
What's the best way to get around this?
In your action method, return Json(object) to return JSON to your page. SomeMethod would be a javascript method that then evaluates the Json object returned. ContentResult by default returns a text/plain as its contentType.
JsonResult is one of the type of MVC action result type which returns the data back to the view or the browser in the form of JSON (JavaScript Object notation format). In this article we will learn about JsonResult by taking scenario to bind view using the JSON Data .
If you need to send JSON in response to a GET, you'll need to explicitly allow the behavior by using JsonRequestBehavior. AllowGet as the second parameter to the Json method. However, there is a chance a malicious user can gain access to the JSON payload through a process known as JSON Hijacking.
Just use the overload of Json(...)
to set the correct content type.
public class HelloController
{
public ActionResult Index()
{
return View()
}
public ActionResult Hello()
{
return Json(new{ greeting = "hello, world!" }, "text/html", JsonRequestBehavior.AllowGet);
}
}
The reason to this is that all Html.Action
invocations are executed directly. Something like:
You got two options:
alert
.public class HelloController
{
YourBusiness _yb;
public HelloController(YourBusiness yb)
{
_yb = yb;
}
public ActionResult Index()
{
return View(yb.GenerateHello())
}
// used for everything but Index
public ActionResult Hello()
{
return Json(new{ greeting = yb.GenerateHello() }, JsonRequestBehavior.AllowGet);
}
}
public class YourBusiness
{
public string GenerateHello()
{
return "Hello wolrd!";
}
}
<script type="text/javascript">
$.get('@Url.Action("Hello")', function(response) {
alert(response.greeting);
}
</script>
Internet Explorer is quite aggressive when it comes to caching. The JSON responses will be changed. I therefore recommend that you also specify no cache for the JSON action:
[OutputCache(Duration = 0, NoStore = true)]
public ActionResult Hello()
{
return Json(new{ greeting = "hello, world!" }, JsonRequestBehavior.AllowGet);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With