Friday, January 27, 2012

Here is some interesting AJAX we started to roll and then abandoned today!

This controller action...

public RenderJsonResult Foo(Guid id)

{

   var program = ProgramRepository.GetById(id);

   var ppMap = new Dictionary<ProgramPlan, string>();

   program.ProgramPlans.ForEach(pp =>

      {

         ppMap.Add(pp, pp.NameStaticAttribute.GetSelectedValue(pp.Id).ToString());

      });

   var result = ppMap.Keys.Select(pp => new

   {

      Id = pp.Id,

      Name = ppMap[pp],

      Offerings = pp.ProgramOfferings.Select(po => new { po.Id, po.Name })

   });

   return RenderJson(result);

}

 
 

...made some new objects and returned them as JSON which kind of looked like this:

{\"PreventCyclicRedundancy\":false,\"Result\":[{\"Plan\":{\"Id\":\"01583ab6-3b8a-4af7-ac68-9fe500ec99a0\",\"Name\":\"alpha\",\"Offerings\":[{\"Id\":\"2660ce9a-73b2-406a-9ff6-9fe500ee6617\",\"Name\":\"one\"},{\"Id\":\"294eac05-83d2-42a6-9cdf-9fe500ee9f17\",\"Name\":\"two\"},{\"Id\":\"80c4ac8b-b2b8-4043-8207-9fe500eef13d\",\"Name\":\"three\"}]}},{\"Plan\":{\"Id\":\"bdf3d257-573d-4685-88d5-9fe500ecaffc\",\"Name\":\"beta\",\"Offerings\":[]}},{\"Plan\":{\"Id\":\"926cf94f-c546-4ec4-a860-9fe500ed8e9a\",\"Name\":\"gamma\",\"Offerings\":[{\"Id\":\"4e729423-3ff9-4abc-bb3c-9fe500ef8ffc\",\"Name\":\"four\"},{\"Id\":\"c3879ef4-80ed-40f9-8a7d-9fe500efc899\",\"Name\":\"five\"}]}}]}

 
 

There was a Razor view like this...

<div class="contentBlock" id="qux">

</div>

<script src="/whatever.js" type="text/javascript"></script>

<script type="text/javascript">

   var programId = '@Model.Program.Id';

   var planLinksContainerSelector = 'qux';

   bar(programId, planLinksContainerSelector);

</script>

 
 

...which reached out to a .js file which called on the Controller Action:

function bar(programId, containerSelector) {
   $.ajax({
      url: '/Program/Foo',
      data: 'id=' + programId,
      success: function (result) {
         var container = $(planLinksContainerSelector);
         _.each(result, function (plan) {
            var planLink = $('<a />');
            planLink.attr('href', '/programplan/edit/?programId=' + programId + '&id=' + plan.Id);
            planLink.text(plan.Name);
            container.append(planLink);
            _.each(plan.Offerings, function (offering) {
               //do offs here
            });
         });
      },
      error: function (a, b, c) {
      }
   });
}

No comments:

Post a Comment