I am extending JsonResult
and need to add properties to the Data
property within it.
public override void ExecuteResult(ControllerContext context)
{
// error checking removed for brevity
this.Data = AppendSomehow(
this.Data, // = new { hello = "hi" }
new { goodbye = "bye" });
base.ExecuteResult(context); // calls javaScriptSerializer.Serialize(this.Data)
}
One option is to convert it into an IDictionary<string, object>
:
private static object AppendSomehow(object data, object additional)
{
var originalDictionary = new RouteValueDictionary(original);
var additionalDictionary = new RouteValueDictionary(additional);
foreach (var kv in additionalDictionary)
originalDictionary.Add(kv.Key, kv.Value);
return originalDictionary;
}
but when passed through a JavaScriptSerializer
this will come out as:
[{"Key":"hello","Value":"hi"},{"Key":"goodbye","Value":"bye"}]
when the desired result is:
{"hello":"hi","goodbye":"bye"}
I could just copy-paste the base.ExecuteResult(ControllerContext)
implementation and modify it to use the solution posted in How to flatten an ExpandoObject returned via JsonResult in asp.net mvc? but that seems a bit dirty when the implemenation already exists.