Monthly Archives: Nov 2017

Validation of DateTime in UK format in C# MVC

In a recent project I was using the bootstrap datetime picker from here:

http://eonasdan.github.io/bootstrap-datetimepicker/

And had it on my view like this:

@Html.TextBoxFor(m => m.EmailDate, “{0:dd/MM/yyyy HH:mm}”, new { @class = “form-control txtModal” })

@Html.ValidationMessageFor(model => model.EmailDate)

Every time I tried to submit the form I would get a jquery validation error telling me that EmailDate was not a valid date. There was a lot of material relating to this problem on Stackoverflow but much was erroneous or misleading. Many suggest that you use data annotations on the model to set the display format…but this only helps a bit if you use an EditorFor rather than a TextBoxFor helper function in the view. It does not get round the validation problem.

The essential problem to overcome is that be default jquery validation expects a date to be in US format (mm/dd/yyy). So, we have to extend the validation logic to allow for UK date formats (dd/mm/yyyy). Once we have done that, we need to cater for the time element that may have been selected using the datetimepicker. The solution below will work for a datepicker or a datetimepicker and can be altered to match any date format as it uses Regex expressions. Add the following to your view script section:

$.validator.addMethod(“date”, function (value, element) {
var stamp = value.split(” “);
var d = new Date();
var validDate = /^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/.test(stamp[0]);
var validTime = /^(([0-1]?[0-9])|([2][0-3])):([0-5]?[0-9])(:([0-5]?[0-9]))?$/i.test(stamp[1]);
return this.optional(element) || (validDate && validTime);
}, “Please enter a valid date and time.”);

We split the datetime value in to two parts and Regex each part separately and then combine the results to avoid having an invalid date and time parts.

Creating a cross site request using jQuery, Ajax and C# MVC

I recently had to create an add-in that allowed dynamic searching. Sometimes this is known as typeahead. This was to be used on our core workflow application which was developed in ClassicASP and is still running happily. Given the size of the data set and the performance required I developed the add-in using C#/MVC that returns a JSONP data set to the calling application for it to render as a dynamic list, any item of which can then be clicked on to use as a shortcut.

There were a couple of challenges with this approach

  • How to deal with CORS
  • How to get AJAX to get the data

In order to deal with the CORS problem, I decided to use JSONP, which is JSON with Padding. To get my controller to return a correctly formatted list it was necessary to create a custom action result class derived from the inbuilt JsonResult class – taken from this fine blog:

https://www.codeguru.com/csharp/.net/net_asp/using-jsonp-in-asp.net-mvc.htm

My controller can then use Linq to SQL to create the data list and return it via:

JsonpResult result = new JsonpResult(amodel);
return result;

The next part is to create the AJAX element so that it does not fall foul of CORS. There is a lot of information regarding this bit on the Internet but not always brought together is a way that makes sense. The key part is to include “callback=?” on the url. I also needed to pass other data items – in my case passed through html5 data tags as there was a version for our live system and test system. My jQuery ended up looking like this:

    $(document.body).on(‘keyup’, ‘#search’, function () {
        var search = $(‘#search’).val();
        var datafield = $(this);
        var associate=datafield.data(‘associate’);
        var domain = datafield.data(‘domain’);
        var analytics = datafield.data(‘analytics’);
        var url = analytics + ‘/Search/GetCases?callback=?’;
        // Only hit the server if the search string is greater than or equal to 3 characters.
        if(search.length >= 3){
            $(“#update”).hide();
    $.getJSON(url, { q: search, associate: associate, domain: domain }, function (data) {
    var output = ‘<ul>’;
    $.each(data,function(key, val){
                    if (val.Url == “#”){
                        output += val.CaseData;
                    }
                    else {
                        output += ‘<a href=”‘ + val.Url + ‘”>’ + val.CaseData + ‘</a>’;
                }
});
            output+='</ul>’;
            $(‘#update’).html(output);
            $(“#update”).show();
     })
    }
})
You can see that I have appended ?callback=? to the url being passed to the getJSON call as well as passing in additional data items. I could have used a standard AJAX call with type: GET, in which case I could have used:

 

dataType: ‘jsonp’,

jsonp: ‘callback’

The callback function can be named explicitly and used in the function(data) part.

With all those bits wired up to my search box and a bit of CSS to style the returned data I ended up with an incredibly performant seach function.

I plan to continue to extend my C#/MVC server app to  offer a number of other centralised features – AJAX file uploads, document encryption and decryption and image manipulation – all of which our very difficult to do in ClassicASP.