Archive for category Web API

MVC Checkbox always true

In my MVC view, I had checkbox, like so:

@Html.CheckBoxFor(m => m.IsComplete)

A button click event called a jQuery method to pull the value of the checkbox to send it to a Web API call:

$("#IsComplete").val()

The problem was that the checkbox value in jQuery was always true, whether or not it was checked on the view. To correct this, I had to abandon the “val()” method and instead used the “:checked” operator:

   var isChecked = $("input[name='IsComplete']:checked").length;
   var isComplete = false;

   if (isChecked == 1) {
       isComplete = true;
   }

Leave a comment

405 Error – The requested resource does not support http method ‘PUT’

While using a PUT request against a Web API call to insert a record into the database, I ran into the 405 error, “The requested resource does not support http method ‘PUT'”. I found a useful link on Stack Overflow that led me to the solution. Here is what worked for me, but I’ll first start by showing the basic call that didn’t work:

    public class ScottController : ApiController {
        public void Put([FromBody]DTO item) {
           ScottRepository.CreateItem(item);
        }
    }

The DTO class holds the fields of the object that I am trying to insert:

        public class DTO {
            public string ID { get; set; }
            public string Name { get; set; }
            public DTO() { }
        }

Those alone were not working. To get the PUT request running, I modified the controller class, adding a RoutePrefix attribute to reference the name that my jQuery call would be using, then added a Route attribute on the PUT request. Here is my final result:

    [RoutePrefix("api/Scott")]
    public class ScottController : ApiController {
        [Route]
        public void Put([FromBody]DTO item) {
           ScottRepository.CreateItem(item);
        }
    }

In case you are curious, here is my jQuery code to call Web API:

      var item = { ID: 'ABC123', Name: 'Bill'};
      $.ajax({
            url: 'http://www.bla.com/api/Scott',
            type: 'PUT',
            dataType: 'json',
            cache: false,
            contentType: "application/json",
            data: JSON.stringify(item),
            success: function (d) {
                // woohoo!                },
            error: function (jqXHR, textStatus, errorThrown) {
                alert('sadness');
            }
      });

Leave a comment

Web API null parameter when POSTing from jQuery

You know that issue where you’re trying to POST a value from jQuery and in the Web API code the parameter is always null? Yeah, that sucks. Hopefully this post will help with your POST problems. I’ll keep this short and explain how I got it to work. First, my Web API method:

public class PermissionsController : ApiController {
     [System.Web.Mvc.HttpPost]
     public HttpResponseMessage Post([FromBody]DTO item)
     {
         string test = item.Name;
         return Request.CreateResponse(HttpStatusCode.OK);
     }
}

I’m passing in more than one field, so I created a data transfer object:

     public class DTO {
         public string Name { get; set; }
         public string AccessType { get; set; }
         public DTO() { }
     }

And my jQuery:

   $.ajax({
      url: 'http://localhost:33166/api/Permissions',
     type: 'POST',
     dataType: 'json',
     cache: false,
     contentType: "application/json",
     data: JSON.stringify(name),
     success: function (d) {
          alert('awesome');
     },
});

Leave a comment

Enabling Session variables in Web API

When trying to access Session variables in Web API, I was seeing the familiar and hated “Object reference not set to an instance of an object”. In fact, the error wasn’t  directed at any variable, it was directed at the Session class itself, HttpContext.Current.Session.

Luckily, I found Oleksandr Kulchytskyi’s article on Code Project, and that saved my bacon, and the rest of breakfast for that matter. It’s very clear, so I recommend following his instructions. I am including my implementation, which used Web API 2, partly because on the Internet, things sometimes disappear, and partly because of a modification I had to make.

I have a class that implements the required interfaces:

using System.Web;
using System.Web.Http.WebHost;
using System.Web.Routing;
using System.Web.SessionState;
namespace Coaster.Controllers {
    public class SessionableControllerHandler : HttpControllerHandler, IRequiresSessionState {
        public SessionableControllerHandler(RouteData routeData)
            : base(routeData) { }
    }

    public class SessionStateRouteHandler : IRouteHandler {
        IHttpHandler IRouteHandler.GetHttpHandler(RequestContext requestContext) {
            return new SessionableControllerHandler(requestContext.RouteData);
        }
    }
}

The one change from Oleksandr’s instructions is the RouteConfig.cs file, since I believe I’m using a later version that he was:

        routes.MapRoute(
            name: "PagingApi",
            url: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        ).RouteHandler = new SessionStateRouteHandler();

Here is where I should include the obligatory comment about Web API, RESTful services, and Session variables, but I won’t. Adding Session variable to Web API made the most sense for improving application performance and making users happy. So there.

Leave a comment

POST command fails to Web API

I had been successfully making GET calls using jQuery to my Web API service, but when I tried a POST, it failed, the request never reaching the breakpoint in my C# code. After using the IE developer tools, I saw that it was pointing to “/sites/apps/MyPost”, and it should have been pointing to “localhost/MyPost”. On the HTML page, there was this line:

 <base href="/sites/apps/" />

I commented-out that line, and the POST command was successful.

Leave a comment