Skip to content

Instantly share code, notes, and snippets.

View danielgreen's full-sized avatar

Daniel Green danielgreen

  • Glasgow, United Kingdom
View GitHub Profile
@danielgreen
danielgreen / jquery.validate.submithandlerfix.js
Created May 29, 2013 09:59
This is an amended fragment of jquery.validate.js (https://github.com/jzaefferer/jquery-validation). The change is to take the value returned from validator.settings.submitHandler.call, and return that value from the handle function. This means that a page that uses submitHandler to take some action upon a successful validation can simply return…
// validate the form on submit
this.submit( function( event ) {
if ( validator.settings.debug ) {
// prevent form submit to be able to see console output
event.preventDefault();
}
function handle() {
var hidden;
if ( validator.settings.submitHandler ) {
if (validator.submitButton) {
@danielgreen
danielgreen / jquery.unobtrusive-ajax.errorfix.js
Created May 29, 2013 10:35
This is an amended fragment of Microsoft jQuery Unobtrusive Ajax (http://nuget.org/packages/Microsoft.jQuery.Unobtrusive.Ajax). The change is to the error property, to ensure that it calls .apply() to invoke the function specified by the data-ajax-failure attribute. Previously it did not call .apply() hence the error handler specified by the pag…
$.extend(options, {
type: element.getAttribute("data-ajax-method") || undefined,
url: element.getAttribute("data-ajax-url") || undefined,
beforeSend: function (xhr) {
var result;
asyncOnBeforeSend(xhr, method);
result = getFunction(element.getAttribute("data-ajax-begin"), ["xhr"]).apply(this, arguments);
if (result !== false) {
loading.show(duration);
}
@danielgreen
danielgreen / AssertValueAttribute.cs
Last active December 17, 2015 20:39
AssertValue is a validation attribute (i.e. a data annotation) that can be applied to a property of a view model class. It causes the property to be invalid unless it has the value specified in the attribute's constructor. The attribute implements IClientValidatable which ties it up with client-side JavaScript in order to replicate the validatio…
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace Validators
{
@danielgreen
danielgreen / AjaxRequestAttribute.cs
Created May 29, 2013 12:49
A filter that can be applied to an MVC action to specify that either Ajax or non-Ajax requests should not be allowed.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Mvc;
namespace SFR.TOR.Web.Filters
{
/// <summary>
@danielgreen
danielgreen / submitHandler.ClearValidationSummary.js
Last active December 17, 2015 20:49
The jQuery Validation library apparently does not clear or hide the Validation Summary list after a successful validation. If the form is valid and will be submitted to the server, it looks better to hide the list. Use a submitHandler callback to deal with this.
// Set the submitHandler callback via the settings object, as is necessary if you are using Unobtrusive Validation.
// If you are not using Unobtrusive Validation then you can set submitHandler in the options object passed to validate().
$("#iTrentExportForm").validate().settings.submitHandler = function (form) {
BlockPage(); // you may want to block the page during the Ajax call
var container = $(form).find("[data-valmsg-summary=true]"),
list = container.find("ul");
if (list && list.length) {
list.empty();
@danielgreen
danielgreen / FormatJavaScriptDate.js
Created May 29, 2013 14:39
Formatting JavaScript dates. Unashamedly nicked from https://gist.github.com/atesgoral/1005948 via http://www.140byt.es/keywords/date. See the linked Gist for more documentation. Alternatively see www.datejs.com and momentjs.com
function formatDate (d,f){return f.replace(/{(.+?)(?::(.*?))?}/g,function(v,c,p){for(v=d["get"+c]()+/h/.test(c)+"";v.length<p;v=0+v);return v})}
// Formats the date as a string e.g. "24/08/2013 17:04"
var formattedDate = formatDate(parsedDate, "{Date:2}/{Month:2}/{FullYear} {Hours:2}:{Minutes:2}");
//Instead of using classical format specifiers like "YYYY", "MM", "HH", "mm" etc.
//this function uses the Date instance getters like getFullYear, getMonth, etc.
//with support for zero-padding.
//For example, instead of:
@danielgreen
danielgreen / PreventAjaxCaching.js
Created May 29, 2013 14:48
Prevent Ajax GET and HEAD calls from receiving cached results. This approach appends a timestamp to the query string to defeat web server caching. See http://api.jquery.com/jQuery.ajax and http://api.jquery.com/jQuery.ajaxSetup. Another approach is to amend server-side code to set an HTTP header such as Expires.
// Disable caching globally, for all Ajax requests
$.ajaxSetup ({
cache: false
});
// Make an Ajax request with caching explicitly disabled
$.ajax({
type: "GET",
cache: false,
url: "http://example.com/GetSomeData"
@danielgreen
danielgreen / ELMAH-1.2-db-SQLServer.sql
Last active December 17, 2015 20:58
ELMAH.MVC is a useful NuGet package that provides an HTTP module to automatically log unhandled ("Yellow Screen Of Death") exceptions in your website, and provides a page (elmah.axd) to allow the exceptions to be reviewed. However, your MVC project is likely to use the built-in HandleErrorAttribute filter which, when custom errors are enabled, c…
/*
ELMAH - Error Logging Modules and Handlers for ASP.NET
Copyright (c) 2004-9 Atif Aziz. All rights reserved.
Author(s):
Atif Aziz, http://www.raboof.com
Phil Haacked, http://haacked.com
@danielgreen
danielgreen / PreserveModelStateOnRedirect.cs
Created May 29, 2013 15:42
If an MVC action has detected validation errors in the model, the errors are held in ModelState. If the action returns a view containing the model, and the jQuery Validate plugin is present on the page, the validation errors are displayed. If the MVC action performs a redirect, however, the model validation errors are lost. Use the PreserveModel…
using System;
using System.Linq;
using System.Collections.Generic;
using System.Web.Mvc;
/* Based on the ModelStateToTempDataAttribute class from MVCContrib */
namespace Web.Filters
{
/// <summary>
/// When a RedirectResult or RedirectToRouteResult is returned from an action, anything in the ViewData.ModelState dictionary will be copied into TempData.
@danielgreen
danielgreen / MVCExtensions.cs
Created May 30, 2013 07:47
Some MVC-specific extension methods. The built-in LabelFor methods do not allow you to specify HTML attributes to be applied to the label element, so these LabelFor extensions plug the gap.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Linq.Expressions;
namespace Web.Extensions
{