Fastest way to return JSON result from a controller
Resturn JSON in MVC controller action
Recently I had to develop a form on a page which loads secondary dropdown list items based on selection in a primary dropdown list.
Because secondary list items are basically children elements of the one selected in primary I just had to run through all children and just return text-value pair object to JavaScript to populate secondary dropdown list.
I tried to minimize code as much as possible so I decided not to use WebAPI controller as I already had SurfaceController for rendering out the form structure, so I decided only to add one more action but this one will return JsonResult instead of ActionResult.
public class FormController : SurfaceController { [HttpPost] public JsonResult GetList(int id) { UmbracoHelper helper = new UmbracoHelper(UmbracoContext.Current); if (helper != null) { IPublishedContent container = helper.TypedContent(id); if (container != null) { return Json(container.Children .Where(c => c.DocumentTypeAlias == "ListItem" && c.GetPropertyValue("title") != null) .Select(l => new { text = l.GetPropertyValue("title"), value = l.Id }), JsonRequestBehavior.AllowGet); } } return null; } }
Since I'm generating anonymous type on the fly which contains value and text property, I do not need to declare return class anywhere which saves.
HttpPost attribute is set to action to ensure request is not cached and we get the values from CMS and not from browser of proxy cache.
On the client side, returned value can be used as an object right away with JQuery because MVC adds the proper headers for JSON content type.
$("#PrimaryList").change(function () { $.post("/umbraco/Surface/Form/GetList?id=" + $(this).val(), function (data) { //Clear all items except first one $("#SecondaryList option:not(:first)").remove(); //Create elements from retrieved data if ($(data) != null) { $(data).each(function (index, item) { $('#SecondaryList').append($('<option>', { value: item.value, text: item.text })); }); } }); });
Disclaimer
Purpose of the code contained in snippets or available for download in this article is solely for learning and demo purposes. Author will not be held responsible for any failure or damages caused due to any other usage.
Comments for this article