Controller.Json Method (Object, String, Encoding)

Creates a JsonResult object that serializes the specified object to JavaScript Object Notation (JSON) format.

Namespace:  System.Web.Mvc
Assembly:  System.Web.Mvc (in System.Web.Mvc.dll)

Syntax

'Declaration
Protected Friend Overridable Function Json ( _
    data As Object, _
    contentType As String, _
    contentEncoding As Encoding _
) As JsonResult
protected internal virtual JsonResult Json(
    Object data,
    string contentType,
    Encoding contentEncoding
)
protected public:
virtual JsonResult^ Json(
    Object^ data, 
    String^ contentType, 
    Encoding^ contentEncoding
)

Parameters

  • data
    Type: System.Object
    The JavaScript object graph to serialize.

Return Value

Type: System.Web.Mvc.JsonResult
The JSON result object that serializes the specified object to JSON format.

Remarks

The data parameter must be serializable. The JavaScriptSerializer class is used to serialize the object. The result object that is prepared by this method is written to the response by the MVC framework when the object is executed.

Examples

The following example shows how to send JSON-formatted data to the browser.

IEnumerable<string> GetDateRangeStr(DateTime start, DateTime endD) {
    while (start <= endD) {
        yield return start.ToShortDateString();
        start = start.AddDays(1);
    }
}

public ActionResult TestJsonContentEnc() {
    return View("TestJson");
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult TestJsonContentEnc(int numDays) {

    return Json(GetDateRangeStr(DateTime.Now,
        DateTime.Now.AddDays(numDays)),
        "text/x-json",
        System.Text.Encoding.UTF8);
}
Private Function GetDateRangeStr(ByVal start As DateTime, ByVal endD As DateTime) As IEnumerable(Of String) 
    While start <= endD 
        
        start = start.AddDays(1) 
    End While 
End Function 

Public Function TestJsonContentEnc() As ActionResult 
    Return View("TestJson") 
End Function 

<AcceptVerbs(HttpVerbs.Post)> _ 
Public Function TestJsonContentEnc(ByVal numDays As Integer) As ActionResult 
    
    Return Json(GetDateRangeStr(DateTime.Now, DateTime.Now.AddDays(numDays)), "text/x-json", System.Text.Encoding.UTF8) 
End Function

See Also

Reference

Controller Class

Json Overload

System.Web.Mvc Namespace