I am implementing, for the first time, Json.NET for my ASP.NET MVC2 site.
My original code looked like this:
[HttpPost]
public ActionResult FindMe(string searchFirstName, string searchLastName)
{
this.searchFirstName = searchFirstName;
this.searchLastName = searchLastName;
IEnumerable<HomePageUser> results = doSearch();
bool success = (results.Count() == 0) ? false : true;
return Json(new
{
success = success,
results = results
});
}
The results were problematic due to the fact that one of the items in the results set is an Enum and I really want the Text value, not the numeric one. Additionally, the date format is a problem.
So, I then found Json.NET and changed my code to this:
[HttpPost]
public JsonNetResult FindMe(string searchFirstName, string searchLastName)
{
this.searchFirstName = searchFirstName;
this.searchLastName = searchLastName;
IEnumerable<HomePageUser> results = doSearch();
bool success = (results.Count() == 0) ? false : true;
JsonNetResult jsonNetResult = new JsonNetResult();
jsonNetResult.SerializerSettings.Converters.Add(new IsoDateTimeConverter());
jsonNetResult.Data = results;// how to add success true/false info?
return jsonNetResult;
}
This fixes the above two issues, but now I'm wondering how to make this seamless with my existing javascript code that was expecting json that looked like:
{
"success":true,
"results":[{
"UserId":545,
"FirstName":"Scott",
"LastName":"Roberson"}]
}
This allowed me to first test for response.success before proceeding to write out the answer, versus moving into the section to handle errors.
So, my question is how do I add a top-level success json node to live beside the results node?
Thanks.
UPDATE:
As is often the case, the act of writing out a question sparked an idea in one of those Doh! moments.
if I add:
var returnPackage = new { success = success, results = results};
then add this to the jsonNetResult.Data like so:
jsonNetResult.Data = returnPackage;
It works perfectly.
Thanks, anyway.
Final code:
[HttpPost]
public JsonNetResult FindMe(string searchFirstName, string searchLastName)
{
this.searchFirstName = searchFirstName;
this.searchLastName = searchLastName;
IEnumerable<HomePageUser> results = doSearch();
bool success = (results.Count() == 0) ? false : true;
var returnPackage = new { success = success, results = results};
JsonNetResult jsonNetResult = new JsonNetResult();
jsonNetResult.SerializerSettings.Converters.Add(new IsoDateTimeConverter());
jsonNetResult.Data = returnPackage;
return jsonNetResult;
}