Monthly Archives: July 2013

ASP.NET Executing code in the header

Something like this will not work

<meta property="og:url" content="<%= Utilities.GetFacebookURL() %>" />

Replaced ‘<%=' with '<%#' [code language="html"] <meta property="og:url" content="<%# Utilities.GetFacebookURL() %>" /> [/code] and added in Master Page code behind [code language="csharp"] protected override void OnLoad(EventArgs e) { base.OnLoad(e); Page.Header.DataBind(); } [/code] Thanks to ASP.NET Resources

ASP.NET CustomValidator AJAX call using jQuery and Webservice (page method)

Markup

<asp:TextBox ID="txtEmail" runat="server" />
<asp:CustomValidator id="CustomValidator3" runat="server" ErrorMessage="- The email address you provided has already been used." Display="None" ControlToValidate="txtEmail" ClientValidationFunction="validateEmail"></asp:CustomValidator>

JavaScript

function validateEmail(oSrc, args) {
	var isValid;
	if (args.Value == '' || args.Value == undefined || $('#<%= txtEmailConfirm.ClientID %>').val() == '') {
		// prevent from calling webservice when unnecessary
		isValid = true;
		args.IsValid = true;
	}
	else {
		$.ajax({
			type: "POST",
			url: "Default.aspx/ValidateEmail",
			contentType: "application/json; charset=utf-8",
			data: "{ 'email':  '" + args.Value + "'}",
			dataType: "json",
			async: false,
			success: function (msg) {
				isValid = msg.d;
			}
			//, error: function () { }
		});
	}
	args.IsValid = isValid;
//        console.log('args.IsValid: ' + args.IsValid);
//        console.log('isValid: ' + isValid);
}

C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using TCUV_contest;

public partial class Default : System.Web.UI.Page
{
    [WebMethod]
    public static bool ValidateEmail(string email)
    {
        return Utilities.EmailAlreadyUsed(email);
    }
}

Sometimes args.IsValid remains unchaged. Useful steps:

  • setting args.IsValid at the end of the code
  • setting $.ajax async property to false (async: false)

Helpful reading: Brian Dobberteen blog