Archive for January, 2016

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 {
     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:

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

Leave a comment

Date formatting for the MVC “DisplayFor” tag

In my view, I had a date that I was displaying using DisplayFor

@Html.DisplayFor(modelItem => item.TranDate)

It was including the time, which I didn’t want. So I tried to include a date format like so:

@Html.DisplayFor(modelItem => item.TranDate, "{0:MM/dd/yyyy}")

This didn’t work, but after looking at the various overloads, it wouldn’t – there was no overload that accepted a format string like there was for TextboxFor, where the format string was working. Instead, what I had to do was add a DisplayFormat tag to the field definition in the model:

public class ServiceVM {
    [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
    public DateTime TranDate { get; set; }

1 Comment

“Specified cast is not valid” accessing a DataReader

I was expecting a double from the database , and I had some simple code to place it into a variable:

double total = double.Parse(reader["total"].ToString());

I received a “Specified cast is not valid” exception. But looking at the value being returned from the database, it wasn’t null, and the value looked like a good double to me. More digits to the right of the decimal place that I had seen with the other doubles, but that’s it. I found a way around it by using the DataReader.GetOrdinal method:

double total = double.Parse(reader.GetOrdinal("total").ToString());

Leave a comment

MetadataException: Unable to load the specified metadata resource

Using Entity Framework, in my context class, I had defined the constructor which pointed to a connection string:

public class EFTestContext : DbContext {
    public EFTestContext()
        : base("name=Entities") {

When I attempted to run the application, I got this message:

 MetadataException: Unable to load the specified metadata resource

Turns out, the connection string was wrong. I had copied the constructor code over from a different project, but when I created the connection string in the web.config, I named it something other than “Entities”. Once I changed the connection string in the constructor, it was good:

: base("name=RightConnString") {

1 Comment

Canceling a JavaScript / jQuery AJAX call

Technically, it’s not really canceled. I just wanted to say that straight away.

I had two drop down lists, the first with departments, and the second with supervisors in those departments. Choosing a value in the first DLL would populate the second DDL as well as loading a bunch of data to display on the page. The second DDL was populated quickly, but the rest of the data could take a while longer to display, and I wanted the users to be able to cancel the long-running request to see the supervisor-specific data.

One problem was that if I selected a supervisor while the department data was still loading, the supervisor-specific data would load, but when the call to the department-wide data finally finished, it would overwrite the supervisor data.

I was using the jQuery “$.ajax” method to call a Web API method. I had tried using the abort() method of the XMLHttpRequest object, the underlying object of the AJAX request, when the second DDL was changed. This didn’t work – the department data was still overwriting the supervisor data – so I had to get hacking.

Here is my solution. I created a variable called “processingRequest”. When the loadData function (which pulled the data from Web API) is started, the variable is set to “true”.  When the request completes, either successfully or it fails, the variable is set to false. Short-running requests will complete before any long-running requests, thus setting the “processingRequest” variable to false. When the long-running requests finished, it will see that the “processingRequest” variable isn’t true, and not perform the page update.

var processingRequest = false;
function loadData(supervisor, dept) {
    var theData = {
        'Supervisor': supervisor,
        'Dept': dept
    processingRequest = true;
    var jqxhr = $.ajax({
        method: 'POST',
        contentType: 'application/json',
        url: uriToMyService,
        data: JSON.stringify(theData)
      .done(function (d) {
          if (processingRequest) {
              processingRequest = false;
      .fail(function (jqXHR, textStatus, errorThrown) {
          console.log('loadData error: ' + errorThrown);
          processingRequest = false;

As I said in the beginning of the post, the request is not canceled, but the results of the request are never shown to the user.


Leave a comment

“One of the identified items was in an invalid format” error using Oracle and .NET

While using the Oracle.ManagedDataAccess assembly to access an Oracle database, I received the error:

 One of the identified items was in an invalid format

I had some pretty typical code, using a parameterized query and passing in values like so:

using (OracleConnection conn = new OracleConnection(connString)) {
   using (OracleCommand comm = new OracleCommand(command, conn)) {
   OracleParameter param = new OracleParameter(":BuildDate", OracleDbType.Date);
   param.Value = buildDate.ToString();

The dynamically generated command string was nothing too fancy, and the line in question looked like:

 "SELECT * FROM Coaster WHERE BuildDate = :buildDate"

No worries – seems straightforward. However, this line was causing the aforementioned error. Once more, the Sad Clown of Life had hit me with a low blow.

I found two ways of fixing this. The first way was to replace the three lines related to the OracleParameter with a single line, like so:

 comm.Parameters.Add(":BuildDate", OracleDbType.Date).Value = buildDate;

Another work around is to remove the parameter code altogether  and put the date right in the query:

 "SELECT * FROM Coaster WHERE BuildDate = '" + buildDate.ToString("dd-MMM-yyyy") + "'"

Not the prettiest result, but it resolved the issue. Feel free to leave a comment if you’ve had this same error and fixed in a better way.

, , ,

Leave a comment