Saturday, April 21, 2012

Newtonsoft.Json may be used in an ASP.NET MVC Project.

I refined the function at the base of this blob of jQuery as given below in the name of updating the question mark in this table.

function TryToCalculate() {
   var checky = "";
   var checkact = "" + $('input[name=act]:checked').val();
   var checkone = "" + $('input[name=one]:checked').val();
   var checktwo = "" + $('input[name=two]:checked').val();
   checky = checky + checkact + checkone + checktwo;
   if (checky.indexOf("undefined") < 0) {
      var callback = function (data) {
         document.getElementById('equals').innerHTML = data.calulation;
      };
      var message = $.ajax({
         type: "POST",
         url: "/Calculation/Go/?act=" + checkact
         + "&one=" + checkone
         + "&two=" + checktwo,
         dataType: 'json',
         success: callback
      }).responseText;
   }
}

 
 

Alright, the AJAX above reaches out to the one action, which I will later refine so that "?" isn't returned all of the time, in this controller:

namespace DelegateExample.Controllers
{
   public class CalculationController : BaseController
   {
      public RenderJsonResult Go(string act, string one, string two)
      {
         var result = new {calulation = "?"};
         return RenderJson(result);
      }
   }
}

 
 

Using the following links...

  1. http://iridescence.no/post/ASPNET-MVC-ActionResult-for-Rendering-JSON-using-JSONNET.aspx
  2. http://james.newtonking.com/pages/json-net.aspx
  3. http://json.codeplex.com/releases/view/85975
  4. http://tom-jaeschke.blogspot.com/2012/01/here-is-some-interesting-ajax-we.html

 
 

...I crafted this:

using System.Web.Mvc;
using Newtonsoft.Json;
namespace DelegateExample.Controllers
{
   public class RenderJsonResult : ActionResult
   {
      public object Result { get; set; }
      
      public override void ExecuteResult(ControllerContext context)
      {
         context.HttpContext.Response.ContentType = "application/json";
         JsonSerializer serializer = new JsonSerializer();
         serializer.Serialize(context.HttpContext.Response.Output, this.Result);
      }
   }
}

 
 

I also had to make a "BaseController" like so. I suppose I could have just stuck the one method below in CalculationController, but a better pattern for this sort of thing begs for a base controller. It seems like every controller could potentially use the method below.

using System.Web.Mvc;
namespace DelegateExample.Controllers
{
   public class BaseController : Controller
   {
      protected RenderJsonResult RenderJson(object obj)
      {
         return new RenderJsonResult { Result = obj };
      }
   }
}

No comments:

Post a Comment