Friday, July 18, 2014

Use the data parameter in jQuery's .ajax to bind to a specific C# type in an ASP.NET Web API implementation.

Let's refactor the application I explain here to bind to a new type which looks like this:

using System;
namespace Security.Models
{
   public class Stuff
   {
      public string RandomGibberish { get; set; }
      public DateTime MomentInTime { get; set; }
   }
}

 
 

I have changed up Index.cshtml to look like so:

@using Security.Utilities
<button id="touchme">touch me</button>
<div id="response"></div>
@section scripts
{
   <script language="javascript">
      $('#touchme').bind('click', function () {
         $.ajax({
            type: "POST",
            url: "/api/values",
            dataType: "json",
            data: {
               RandomGibberish: '@ViewBag.SessionKeyForIdentity',
               MomentInTime: '@TimeUtility.GetTime()'
            },
            success: function (result) {
               $("#response").html(result);
            }
         });
      });
   </script>
}

 
 

I have changed up ValuesController also. It looks like this:

using System;
using System.Security.Principal;
using System.Threading;
using System.Web.Http;
using Security.Models;
using Security.Utilities;
namespace Security.Controllers
{
   public class ValuesController : ApiController
   {
      public string Post([FromBody] Stuff stuff)
      {
         try
         {
            IdentityUtility.RefreshIdentity(stuff.RandomGibberish);
            IPrincipal principal = Thread.CurrentPrincipal;
            if (String.IsNullOrEmpty(principal.Identity.Name))
            {
               return "The current user is anonymous.";
            } else {
               return "The current user is: " + principal.Identity.Name + "!";
            }
         }
         catch(Exception exception)
         {
            return "Error at " + stuff.MomentInTime + ": " + exception.Message;
         }
      }
   }
}

 
 

Nice.

No comments:

Post a Comment