jQuery Validation in ASP.NET - asp.net

i have a strange situation may its a easy fix or something i may be missing but here is the question.
i have a asp.net form with master page and my validation works great without any problem but the problems starts when i try to hook my click event to the server side,
here is what i meant:
i have a form with few fields on it and if the form is empty than it should STOP submitting, otherwise allow me to execute the server side script
but its not happening, even my form is in invalid state (i do get error message saying i have to enter the required fileds) but still executing my server side script.
i would like to execute my server side script only if the form is in valid state.
here is my code:
my master page
<%# Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>jQuery Validation in ASP.NET Master Page</title>
<script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>
<script src="Scripts/jquery-1.3.2-vsdoc2.js" type="text/javascript"></script>
<script src="Scripts/jquery.validate.js" type="text/javascript"></script>
<asp:ContentPlaceHolder id="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
my content page:
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<script type="text/javascript">
$(document).ready(function() {
$("#aspnetForm").validate({
rules: {
<%=txtName.UniqueID %>: {
minlength: 2,
required: true
},
<%=txtEmail.UniqueID %>: {
required: true,
email:true
}
}, messages: {
<%=txtName.UniqueID %>:{
required: "* Required Field *",
minlength: "* Please enter atleast 2 characters *"
}
}
});
});
</script>
Name: <asp:TextBox ID="txtName" MaxLength="30" runat="server" /><br />
Email: <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox><br />
<asp:Button ID="btnSubmit" runat="server" onclick="SubmitTheForm();" Text="Submit" />
</asp:Content>
function SubmitTheForm() {
SaveTheForm();
}
function SaveTheForm() {
debugger;
var request = buildNewContactRequest();
ContactServiceProxy.invoke({ serviceMethod: "PostNewContact",
data: { request: request },
callback: function(response) {
processCompletedContactStore(response);
},
error: function(xhr, errorMsg, thrown) {
postErrorAndUnBlockUI(xhr, errorMsg, thrown);
}
});
return false;
}
i have tried both ways
1)
$(document).ready(function() {
$("#btnSubmit").click(function(event) {
event.preventDefault();
SaveTheForm();
});
});
2)
<asp:Button ID="btnSubmit" runat="server" onclick="SubmitTheForm();
function SubmitTheForm() {
SaveTheForm();
}

you're posting your data without checking if the form is valid or not
I think you have to use something like this
function SubmitTheForm() {
if ($("#aspnetForm").valid()) SaveTheForm();
}

Sorry, I'm giving you bad advice. Forget my previous entry. What is the SubmitTheForm() method? You're using the jQuery validation plug in, so you should just need to attach the validation stuff to the form and all should be right with the world.

I think your button onclick needs to be
return SaveTheForm();
As in:
<asp:Button ID="btnSubmit" runat="server" onclick="return SubmitTheForm();" Text="Submit" />

Do you try to put the jQuery code script in the Head ContentPlaceHolder

Related

FancyBox doesn't trigger when using it in UserControl

I have ASP.Net Masterpage design & have to user a Fancybox to show videos as modal, When i show videos on a ContenPage & place all related scripts to FB on that page then it works fine for that page without any issue. But i also need Top 10 Videos to be shown on some page as a user control. What i do is that i create a User Control & put all the related scripts in that user control except the main jQuery which i user in masterpage & download as CDE.
In this case fancybox doesnt trigger.
I am to make it work if i black fancy-box related scripts on all contents page which i dont want to.
I want script to be in userControl
I have placed my sample code for user control & master Page below.
USER CONTROL
<%# Control Language="C#" AutoEventWireup="true" CodeFile="ucMostPopular.ascx.cs" Inherits="ucMostPopular" %>
<script src="<%= Helper.ResolveUrl("~/scripts/fancybox/jquery.fancybox-1.3.4.js") %>" type="text/javascript"></script>
<link href="<%= Helper.ResolveUrl("~/styles/english-jquery.fancybox-1.3.4.css") %>" rel="stylesheet" type="text/css" />
<script type="text/javascript">
//Code to Reinitialize Fancybox script when using update panel START
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);
function InitializeRequest(sender, args) { }
function EndRequest(sender, args) { InitMyFancyBox(); }
$(document).ready(function () {
InitMyFancyBox();
});
function InitMyFancyBox() {
$(document).ready(function () {
$(".youtube").click(function () {
// first, get the value from the alt attribute
var newTitle = $(this).find("img").attr("alt"); // Get alt from image
$.fancybox({
'padding': 0,
'autoScale': false,
'transitionIn': 'none',
'transitionOut': 'none',
//'title': this.title, // we will replace this line
'title': newTitle, //<--- this will do the trick
'width': 680,
'height': 495,
'href': this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
'type': 'swf',
'swf': { 'wmode': 'transparent', 'allowfullscreen': 'true' }
});
// alert(this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'));
$.ajax({
type: "POST",
url: "UpdateVideoViews.aspx?youtubeVideoID="+this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
});
return false;
});
});
}
</script>
<!-- Videos -->
<div id="Videos" class="tab_text">
<div id="popular-videos-wrapper">
<asp:Repeater ID="rptPopularVideos" runat="server" EnableViewState="False" >
<ItemTemplate>
<div class="popular-article-title">
<asp:Label ID="lblCounter" CssClass="lblCounter" runat="server" Text='<%# Container.ItemIndex + 1 %>' > </asp:Label>
<asp:HyperLink ID="hylnkArticle" CssClass="popular-youtube-links" ToolTip ='<%# Eval("VideoTitle")%>' NavigateUrl='<%# generateVideoURL(Eval("VideoYoutubeID")) %>' runat="server" BorderWidth="0">
<asp:Label ID="lblArticleTitle" Text='<%# getVideoTitle(Eval("VideoTitle"))%>' runat="server" ></asp:Label>
</asp:HyperLink>
</div>
</ItemTemplate>
</asp:Repeater>
</div>
</div>
<!-- Videos -->
MASTER PAGE
<%# Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="SiteMasterPage" %>
<%# Register Src="~/en/UserControls/ucLiquidCarousel.ascx" TagName="ucLiquidCarousel" TagPrefix="uc"%>
<%# Register Src="~/en/UserControls/ucNewsTicker.ascx" TagName="ucTicker" TagPrefix="uc"%>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title></title>
<asp:Literal ID="litCtrMetaForSM" runat="server"></asp:Literal>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<link rel="shortcut icon" href="http://www.alshindagah.com/favicon.ico">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
<link href="../styles/english_css.css" rel="stylesheet" type="text/css" />
<link href="../styles/horizontal-menu-english.css" rel="stylesheet" type="text/css" />
<asp:ContentPlaceHolder ID="head" runat="server"> </asp:ContentPlaceHolder>
<script type="text/javascript">
.....
//Other scripts
.....
</script>
I am not sure why this is not working i have moved script related to fancy box on masterpage then it worked only for default page & failed on other pages.
I also used ResolveURL(...) that didn't work either
I dont get any error regarding script.
I would appreciate help in this regard so that my fancybox will work by placing all the scripts related to fancybox from usercontrol it self

UserControl Raise Events

I add an onfocus event to a web user control (.ascx) expection it to raise event when it gets focus but it doesn't. Is it not intended to work this way and how can I get it to raise the event? Here is sample below, but it doesn't work.
<%# Control Language="vb" AutoEventWireup="false" CodeBehind="WebUserControl1.ascx.vb"
Inherits="RaiseEventUserControl.WebUserControl1" %>
<div style="padding: 5px; background-color: #C0C0C0">
TB1:
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<br />
TB2:
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</div>
<%# Register Src="WebUserControl1.ascx" TagName="WebUserControl1" TagPrefix="uc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function RaiseEvent(obj) {
alert("Event was raised for: " + obj.id)
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<uc1:WebUserControl1 ID="WebUserControl11" runat="server" onfocus="RaiseEvent(this)" />
<br />
<uc1:WebUserControl1 ID="WebUserControl12" runat="server" onfocus="RaiseEvent(this)" />
</div>
</form>
</body>
</html>
This can be achieved using jquery. In your head element, add the following:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('input[name^="WebUserControl"]').focusin(function () {
$(this).val("i have focus");
});
});
</script>
What this does is, grabs the input elements whose name starts with "WebUserControl" and adds a "got focus" event. The handler for that event places "i have focus" as the value for that input element.
The way that this would be rendered to the page is that a "onFocus" attribute would be added to the div that represents the control. This is not something that supports focus. You might add the "onFocus" item to say your first text field in the control or something similar to be able to raise the event if needed.

asp.net jquery how to use Plugin/Validation with web content

I have a asp.net web content from that have a asp.net textbox and I want to use Plugin/Validation but it is not working with me here is my code:
<%# Page Title="" Language="C#" MasterPageFile="~/Master.Master" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="IMAM_APPLICATION.WebForm1" %>
<%# Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="asp" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
<script src="js/jquery-1.4.1.js" type="text/javascript"></script>
<script src="js/jquery.validate.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$.validator.addMethod("#<%=TextBox1.ClientID %>", function(value, element) {
return this.optional(element) || /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,16}$/i.test(value);
}, "Passwords are 8-16 characters with uppercase letters, lowercase letters and at least one number.");
});
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="ContentPlaceHolder2" runat="server">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</asp:Content>
Well I am unsure what the problem is as this does not tell me much "not working".
Just looking at your code I am trying to see might cause it not to work.
First you don't have the validate method hooked up to any form. I don't think you can run it without hooking it up to a form tag.
// from the validation documentation
$("#commentForm").validate();
Notice how they tie the validate field.
Next
I think your doing your .addMethod wrong
$(document).ready(function() {
$.validator.addMethod("#<%=TextBox1.ClientID %>", function(value, element) {
return this.optional(element) || /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,16}$/i.test(value);
}, "Passwords are 8-16 characters with uppercase letters, lowercase letters and at least one number.");
});
You have what is above but if you look at the documentation.
addMethod( name, method, [message] )
jQuery.validator.addMethod("math", function(value, element, params) {
return this.optional(element) || value == params[0] + params[1];
}, jQuery.format("Please enter the correct value for {0} + {1}"));
see how the first paramter is "name" not "id". Name is like the name of this new method.
So this addMethod could be called "Test101" that would be the name. Or like in the examle you see they named it "math"
next you would do something like this
$("#commentForm").validate
(
rules:
{
txtBoxIdName:
{
math: true;
}
}
);
So it would me something like this. You would put the textboxId in the validate method of the form and then you call your .addMethod inside that id. In my case I used the .addMethod called "math" and I believe you just set it to "true" to make it required and to run.
I have not tested this so I will try to find some examples that actually run.
Edit
Here is what the master page.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<asp:ContentPlaceHolder id="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
see it does have a form id and when you hook this master page with an aspx page you should have this.
<title>
</title>
<script>try { for(var lastpass_iter=0; lastpass_iter < document.forms.length; lastpass_iter++){ var lastpass_f = document.forms[lastpass_iter]; if(typeof(lastpass_f.lpsubmitorig)=="undefined"){ if (typeof(lastpass_f.submit) == "function") { lastpass_f.lpsubmitorig = lastpass_f.submit; lastpass_f.submit = function(){ var form = this; try { if (document.documentElement && 'createEvent' in document) { var forms = document.getElementsByTagName('form'); for (var i=0 ; i<forms.length ; ++i) if (forms[i]==form) { var element = document.createElement('lpformsubmitdataelement'); element.setAttribute('formnum',i); element.setAttribute('from','submithook'); document.documentElement.appendChild(element); var evt = document.createEvent('Events'); evt.initEvent('lpformsubmit',true,false); element.dispatchEvent(evt); break; } } } catch (e) {} try { form.lpsubmitorig(); } catch (e) {} } } } }} catch (e) {}</script></head><body>
<form name="aspnetForm" method="post" action="Default2.aspx" id="aspnetForm">
<div>
<input name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMTY1NDU2MTA1MmRkJ6rATKUz8lX/wrHNVcM8o9fwof8=" type="hidden">
</div>
<div>
</div>
</form>
</body></html>
So try that if that will be good enough for hooking it up.

jQuery errorContainer practice

I'm trying to be able to place the error message when using jQuery validation to a asp.net label if the textbox is empty.
please advice how to modify my code to get that!!
here is my code:
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
<script src="js/jquery-1.4.1.js" type="text/javascript"></script>
<script src="js/jquery.validate.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#aspnetForm").validate({
errorContainer: "#<%=TextBox1 %>",
errorLabelContainer: "#<%=TextBox1 %> #<%=Label1 %>",
wrapper: "li", debug: true,
submitHandler: function() { alert("Submitted!") }
})
});
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="ContentPlaceHolder2" runat="server">
<p style="height: 313px">
<asp:TextBox ID="TextBox1" runat="server" class="required"></asp:TextBox>
<asp:Label ID="Label1" runat="server" Text="Label" ></asp:Label>
</p>
</asp:Content>
I think
"#<%=TextBox1 %>"
means write the value of the default property of the textbox, which is the .Text property.
You should use
"#<%=TextBox1.ID %>"
and
"#<%=TextBox1.ID %> #<%=Label1.ID %>"
No to disqualify what you are doing now but I can't wrap my head around why you add a new plugin like JQ validation when you have a simple case of a required field validator which is a built in .net control

how to use ajax in JQuery

I have that works fine without Script manager. but if I add script manager that getting an error: sys undefined.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Block-ui-pageload.aspx.cs" Inherits="Block_ui_pageload" %>
<%# Register Assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
Namespace="System.Web.UI" TagPrefix="asp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
<script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>
<script src="Scripts/jquery.blockUI.js" type="text/javascript"></script>
</head>
<body>
<form id="form1" runat="server">
<div id="divConfirmBox1">
<asp:GridView ID="gvCategories" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="Category Name">
<ItemTemplate>
<asp:Label ID="lblCategoryName" runat="server" Text='<%# Eval("CategoryName") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<input type="button" value="Delete" onclick="showDeleteConfirmation('<%# Eval(" CategoryId")=CategoryId") %=% />')" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<div id="divConfirmBox" style="display:none">
Are you sure you want to delete this record?
<input type="button" value="No" />
</div>
</div>
</form>
</body>
</html>
<script language="javascript" type="text/javascript">
$(function () {
$('#divConfirmBox1').block({ message: $('#divConfirmBox') });
});
$(function () {
$('#divConfirmBox').click(function (event) {
$('#divConfirmBox1').unblock();
});
});
</script>
initially during the page load . I am blocking the screen(PAge). once the user clicks the button the page is unblocked.
is there anything wrong in the Syntax whiling working with Ajax script manager
You should move the jQuery code into $(document).ready. I suspect you're preventing certain scripts from loading appropriately by running the code inline rather than in .ready. I'm running the same version of jQuery (but not UI block) with ScriptManager in 3.5 right now, no prob.
AJAX is not a thing - its a bunch of technologies put together to achieve asynchronous communication. Yes, you have some JavaScript coding in there, but none of them actually do anything 'ajaxian' - a good example of something really AJAX-style would be an validation of a (registration) form or something like that. You'd set some oberservers for some fields and validate them whilst the user is still making inputs on other fields...
I think what you're looking for is noConflict. It's been a while since I've used asp.net ajax but if I'm not mistaken, there is a $ function defined.
In the web.config we need to add the follwing code within tag.
then the problem was solved
every thing was working fine

Resources