Fremus.co.za

Demistifying Life and Web Development

Daily Code – Day 1 – ASP.NET MVC: Using Json() to create dynamic types

Do you ever have to return more than one result set, or dataset for that matter to some UI? If for instance you have a piece of UI that allows users to create something new with by entering a value into a textbox AND by selecting a value from a dropdown list AND you are displaying existing (already added) data in a table below the dropdown and the textbox and they all appear on a modal dialog. Logic tells me that when I click to activate the dialogue the dropdownlist and the table with the data must be populated with data. It also tells me that its not feasible to make two jQuery ajax calls, one for the data in the table and another for the data in the dropdown. What to do? Return arrays of objects with one ajax call and bind it to the UI. How do you return arrays of objects in ASP.NET MVC? Well you can create dynamic objects like this:


        [HttpPost]
        public JsonResult GetOfferings()
        {
            offerings = new OfferingRepository();
            offerings.GetOfferings();
            offeringTypes = new OfferingTypeRepository();
            offeringTypes.GetOfferingTypes();
            return Json(
                new
                {
                    Offerings = offerings.Offerings.Select(t =>
                        new
                        {
                            OfferingName = t.OfferingName,
                            OfferingId = t.Id
                        }),
                    OfferingTypes = offeringTypes.OfferingTypes.Select(t =>
                        new {
                            OfferingTypeName = t.OfferingTypeName,
                            OfferingTypeId = t.Id
                        })
                });
        }
  • Share/Bookmark
posted by fr3dr1k in ASP.NET MVC and have No Comments

Place your comment

Please fill your data and comment below.
Name
Email
Website
Your comment
Get Adobe Flash playerPlugin by wpburn.com wordpress themes