System.Web.Mvc.JsonResult
usea the old JavaScriptSerializer
class, which doesn't know anything about the DataAnnotiations assembly. You need to use the DataContractJsonSerializer instead.
You can use this instead on JsonResult if you so desire:
public class DataContractJsonResult : JsonResult
{
public DataContractJsonResult(object data)
{
Data = data;
}
public DataContractJsonResult()
{
}
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
if (JsonRequestBehavior == JsonRequestBehavior.DenyGet &&
String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException("This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.");
}
HttpResponseBase response = context.HttpContext.Response;
if (!string.IsNullOrEmpty(ContentType))
{
response.ContentType = ContentType;
}
else
{
response.ContentType = "application/json";
}
if (ContentEncoding != null)
{
response.ContentEncoding = ContentEncoding;
}
if (Data != null)
{
var serializer = new DataContractJsonSerializer(Data.GetType());
var ms = new MemoryStream();
serializer.WriteObject(ms, Data);
string json = Encoding.UTF8.GetString(ms.ToArray());
response.Write(json);
}
}
}
(I referenced the ASP.NET MVC source code to create this. Not sure if I have to credit it in some way. Well, more than this aside already is, that is. :))
You can also add this to a base class from which your controllers inherit:
protected JsonResult DataContractJson(object data)
{
return new DataContractJsonResult(data);
}