The MVC model is null when posting

I had an MVC view that I was using to update my data using a POST method by using a Bootstrap modal popup window. Everything seemed fine, but when I put a breakpoint in my controller action, my model was null. My very simple action:

       [HttpPost]
       public ActionResult Update(Coaster model) {
           return View();
       }

I’m going to give away the ending. The problem was that my form didn’t have the “name” property attached to the “input” tag. I thought the “id” property would be enough to send my model from the view to the controller, but it wasn’t. So instead of this:

<input type="text" id="Code" class="form-control" />

I had to have this:

<input type="text" id="Code" name="Coaster" class="form-control" />


		
Advertisements

Leave a comment

jQuery DatePicker – Removing time from a DatePicker control

I had an MVC view with a TextBox control binding to a model property

@Html.TextBoxFor(model => model.Date, String.Empty, new { @class = "form-control" })

This control was bound to a jQuery DatePicker control:

    $(document).ready(function () {
        $("#Date").datepicker({
            minDate: 0
        });
    });

My problem was that when the model was bound from the database, the DatePicker would also show the time, not just the date like I wanted:

 

 

 

 

 

 

 

 

The fix for this is to make the second parameter a format string with only the date:

@Html.TextBoxFor(model => model.IssueDate, "{0:d}", new { @class = "form-control" })

Leave a comment

Updating an Oracle LONG column

Want to update an Oracle LONG value? Having problems? Well, you’re in luck. Do update the field, run this bit of code. Yes, it’s not an lovely as a one-line UPDATE statement, but sometimes, you have to do it the ugly way:

DECLARE
 coasterDesc varchar2(5000); 
BEGIN
 coasterDesc := 'Some really, really, REALLY long text goes here.';
 UPDATE coasters SET coaster_description = coasterDesc WHERE coaster_id = '12345'; 
END;

Leave a comment

Web API getting 404

When trying to perform a simple GET request using Web API in my MVC application, I was getting a 404 message. I was accessing it through Ajax, and the URL was correct:

    $.ajax({
        url: 'http://localhost:1234/api/UserApi',
        type: 'GET',
        cache: false,
        contentType: 'application/json'
    });

The problem was actually environmental. At a particular job site, the machines were locked down, including not being able to run PowerShell command – thus, an impediment to using NuGet. So I had to do several things to get my project working, but hopefully, if you’re having a similar issue, one of these is the key for you.

Several DLLs needed to be replaced, as the version were too old:

  • System.Net.Http
  • System.Net.Http.Formatting
  • System.Web.Http

The WebApiConfig.cs file was missing from the App_Start folder, so I added it:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace ScottProject.App_Start {
    public class WebApiConfig {
        public static void Register(HttpConfiguration config) {
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

The Global.ascx.cs file was missing the referene to the WebApiConfig file:

     protected void Application_Start() {
         // Other file snipped out
         GlobalConfiguration.Configure(WebApiConfig.Register);
     }

So this particular situation was specific to my situation, but perhaps one of those issues will help someone else.

Leave a comment

Slow multiple jQuery autocomplete fields

I’m a fan of the jQuery autocomplete control. I had a page that worked great with one autocomplete control, but after I added a second, that second control was horribly slow (the first was unchanged). Both controls were defined similar to the one here:

$("#Coaster").autocomplete({
    source: function (request, response) {
        if (request.term.length < 4) {
            return;
        }
        var coaster = new Array();
        $.ajax({
            async: false,
            cache: false,
            type: "POST",
            url: uri + "MyControll/Autocomplete",
            data: { "term": request.term },
            success: function (data) {
                for (var i = 0; i < data.length ; i++) {
                    customer[i] = data[i];
                }
            }
        });
        response(coaster);
    },
    select: function (event, ui) {
        $("#CoasterID").val(ui.item.Id);
    }
});

In order to get the second control to respond within a reasonable period of time, I added this code to the end of the Ajax method, which resolved the problem:

$("#Coaster").autocomplete({

        $.ajax({
 …
        })._renderItem = function (ul, item) {
            return $("<li></li>")
                .data("item.autocomplete", item)
        };
});

Leave a comment

JavaScript countdown timer

I needed a timer to let users know they have fifteen minutes to complete a request. First, the script:

    var end = new Date().getTime() + (15 * 60000);

    var d = setInterval(function () {

        var now = new Date().getTime();
        var distance = end - now;

        var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
        var seconds = Math.floor((distance % (1000 * 60)) / 1000);

        document.getElementById("timer").innerHTML = "

Please complete the " +             "request within 15 minutes.
Time remaining: " + minutes + ":" + seconds + "

";         if (distance

The “timer” DIV here is without all the awesome styling I have on the one in my application, but I’m sure you can center your own text:

Leave a comment

When your Boolean parameter says “oncheck” in JavaScript and what to do about it

In my MVC application, I was building a table using a partial view. One column was an HTML link whose onclick event was bound to the “show” method, and this method took two parameters, a string and a boolean:

 <table>
   <tr>
      <td><a onclick="show('@item.ID', '@item.IsVisible')">Click Me!</a></td>
   </td>
 </table>

Inside the “show” method, notice the “visible” checkbox. I am simply setting the “checked” property to true or false, depending on the value of the “visible” parameter:

function show(id, visible) {
 $("#id").val(id);
 $('#visible').prop('checked', visible);
}

When running this code, I got strange behavior, and using the Developer Tools (F12 in IE), I noticed that the string generating the edit button line looked like this:

 <td><a onclick="show('1', 'checked')">Click Me!</a></td>

Huh. How did that “checked” get in there? When I ran the debugger, and MVC code was correctly binding the Boolean variable to either “True” or “False”, so what’s with this “checked” things I’m seeing?

There were two problems here. First, I needed to modify the MVC code, calling the “ToString” method on the Boolean property:

    <td><a onclick="show('@item.ID', '@item.IsVisible.ToString()')">Click Me!</a></td>

Second, this would return “True” or “False”, with the first letter capitalized. JavaScript needs those values in lower case. So I set up a ternary operator to handle that:

function show(id, visible) {
  $('#visible').prop('checked', visible == "True" ? true : false);
}

Fixed!

Leave a comment