'controltovalidate' error in IE8 - c#

I'm getting a JavaScript error (in IE only of course) and I can't figure out why. I assumed it was a trailing comma or something but I can't find one. I'm hoping I'm overlooking something and maybe one of you can see what I missed.
My control and custom validator:
<asp:TextBox runat="server" ID="txtName" MaxLength="100" CssClass="styled" Columns="50" />
<asp:CustomValidator runat="server" ID="cvName" ErrorMessage="Enter a valid contact name or email address" ControlToValidate="txtName" Display="None" ValidationGroup="PlatformContact" ClientValidationFunction="doesUserExist" />
<asp:ValidatorCalloutExtender ID="vceName" runat="server" TargetControlID="cvName" WarningIconImageUrl="~/img/icons/ic_asterisk.gif" CssClass="validatorStyled" PopupPosition="Right" CloseImageUrl="~/img/icons/ic_x_close_orange.png" />
<asp:RequiredFieldValidator runat="server" ID="valName" ErrorMessage="Enter a contact name or email address" ControlToValidate="txtName" Display="None" ValidationGroup="PlatformContact" />
<asp:ValidatorCalloutExtender ID="vceNameRequired" runat="server" TargetControlID="valName" WarningIconImageUrl="~/img/icons/ic_asterisk.gif" CssClass="validatorStyled" PopupPosition="Right" CloseImageUrl="~/img/icons/ic_x_close_orange.png" />
And here is the JavaScript/jQuery I am using:
<script language="javascript" type="text/javascript">
var userExists = true;
function doesUserExist(source, args) {
var txtName = $('#<%= txtName.ClientID %>').val();
$.ajaxSetup({ cache: false });
$.ajax({
type: "POST",
contentType: "application/json",
data: "{name:'" + txtName + "'}",
url: "ManageMyContacts.aspx/DoesUserExist",
dataType: "json",
success: function (result) {
userExists = result.d;
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//Something bad happened,redirect to login page
window.location.href = '<%= ResolveUrl("~/Default.aspx") %>';
}
});
args.IsValid = userExists;
}
</script>
Any insight is greatly appreciated.
EDIT: JavaScript error
Message: 'controltovalidate' is null or not an object
Here is the WebMethod I user to check for the user name (in the code behind)
[WebMethod(EnableSession = true)]
public static bool DoesUserExist(string name)
{
ManageMyContactsService service = new ManageMyContactsService();
int index = name.IndexOf("[") + 1;
if (index > 0)
{
string email = name.Substring(index, name.Length - (index + 1));
return service.DoesUserExist(email);
}
else if (name.IndexOf("#") == -1)
return false;
else
return service.DoesUserExist(name);
}
I noticed the doesUserExist function gets called twice for some reason, can anyone tell why from this code?

It appears an UpdatePanel was causing the second ajax call and was causing IE to throw a JS error. Worked fine in the other browsers but not IE7/8!
Hope that helps someone with a similar issue.

Related

Struggling to ASP.NET C# Ajax novice question

I changed the code with a simple like these
<script src="http://code.jquery.com/jquery-1.10.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#RadioButtonYes').click(function () {
var enterdata = document.getElementById("RadioButtonYes").value;
$.ajax({
type: "GET",
url: "radiobutton03ask.aspx/SyncData",
contentType: "application/json charset=utf-8",
dataType: "json",
data: { 'data': enterdata },
success: function (response) {
text1 = "ajaxyes";
alert(text1);
},
failure: function (response) {
alert(response.d);
}
});
});
$('#RadioButtonNo').click(function () {
var enterdata = document.getElementById("RadioButtonNo").value;
$.ajax({
type: "GET",
url: "radiobutton03ask.aspx/SyncData",
contentType: "application/json charset=utf-8",
dataType: "json",
data: { 'data': enterdata },
success: function (response) {
text2 = "ajaxno";
alert(text2);
},
failure: function (response) {
alert(response.d);
}
});
});
});
</script>
<div>
<asp:RadioButton ID="RadioButtonYes" Text="Yes" runat="server" Checked="true" GroupName="G" />
<asp:RadioButton ID="RadioButtonNo" Text="No" runat="server" GroupName="G" />
</div>
.cs side
I tried to add some debugging messages, but it didn't work.
public partial class Radio_Button__radiobutton03ask : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public void SyncData(string data)
{
if (data != "")
{
if (data == "RadioButtonYes")
{
Response.Write("SyncDataYes");
//return RadioButtonYes;
}
else if (data == "RadioButtonNo")
{
Response.Write("SyncDataNo");
//return RadioButtonNo;
}
else
{
Response.Write("SyncDataOther");
}
}
}
}
I am helping the company to debug some old projects(C# webforms), but struggling to simple ajax.
The goal is when pressing the radio button run ajax "ajaxyes" and .cs "SyncDataYes" message normally, but the above code does not respond when pressed.
I have tried alot of fixes i found online but none seem to work well for, if someone could help, it would be greatly appreciated.
first, there is a LOT of issues here.
first up:
[WebMethod]
public void SyncData(string data)
Why are you marking/making the routine as "void". Void of course in c# means that the function will NOT return anything!!!! - That should be a first obvious issue!
And since you using this inside of the web page (as opposed to a separate asmx page? Then you need to set the routine as static - since NO page class instance will have been created here (there is NOT post back).
next up:
Response.Write("SyncDataNo");
WHY would you try and use Response.Write? Response write is ONLY for writing into a web page. But the WHOLE IDEA of ajax is the web page is not and will not be sent up to the server for code behind to operate on. So, response write does not make sense AT ALL here! It can't be used, and you can EVEN see that the compiler does not allow this (now that you fixed and removed the void from that routine).
A so called "ajax" call?
The idea here is that you do NOT have to post back the web page. This is great since you don't get the browser "spinner" and all that waiting time. It also great since it runs VERY fast since you don't and are NOT posting the web page back to the server.
Of course the big downside is then the code behind can't see nor use, nor modify any of the controls on the web page. (since the web page is still sitting on the users desktop). So code behind for a web method can't see nor modify controls on the page (the calling JavaScript and ajax call HAS do to that change of controls).
So, lets use all of the above information, and fix this code.
Lets make a simple C to F temperature converter.
So, first up, that web method is to return a value, so we remove the void.
next up, as I stated, the page class "instance" is NOT re-created when we call such a web method, so that method ALSO MUST be marked as static. (I assume you know what that means, right???).
Ok. So the web method should look like this:
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static Double ConvertToC(Double MyC)
{
Double CelResult = (MyC * 1.8) + 32;
return CelResult;
}
So, we HAVE to make this routine static. (the page class is not re-reated, and the web page is STILL sitting on the users desktop).
So, say our markup looks like this:
<div style="text-align:right;width:20%">
<label style="font-size:large">Enter Celsious Tempature</label>
<asp:TextBox ID="txtC" runat="server" style="font-size:large;margin-left:5px;text-align:center"
TextMode="Number" Width="80px" Wrap="False"
ClientIDMode="Static">
</asp:TextBox>
<br /> <br />
<div style="text-align:center">
<asp:Button ID="cmdConvert" runat="server" Text="Convert to °F" CssClass="btn"
OnClientClick="MyConvert();return false"/>
</div>
<br />
<label style="font-size:large">Fahrenheit</label>
<asp:TextBox ID="txtF" runat="server" style="font-size:large;margin-left:5px;text-align:center"
Width="80px" Wrap="false"
ClientIDMode="Static">
</asp:TextBox>
</div>
<script>
function MyConvert() {
var txtC = $("#txtC");
var txtF = $("#txtF");
$.ajax({
type: "POST",
url: "Autocom.aspx/ConvertToC",
data: JSON.stringify({ MyC: txtC.val()}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (MyReturn) {
txtF.val(MyReturn.d);
},
error: function (xhr, status, error) {
var errorMessage = xhr.status + ': ' + xhr.statusText
alert('Error - ' + errorMessage)
}
});
}
I'm also a bit lazy, so I used clientID mode = static, as that makes the jQuery selector nice and easy to type in.
So, when we run the above, we get this result:
so, now your "mess".
it not particular what you goal here is with your sample.
(going for coffee, but study, and try the above).
Edit: Try this sample code
Your c# method in the page:
[WebMethod]
public static string SyncData(string data)
{
string sResult = "";
if (data != "")
{
if (data == "Yes")
{
sResult = "SyncDataYes";
}
else if (data == "No")
{
sResult = "SyncDataNo";
}
else
{
sResult = "SyncDataOther";
}
}
return sResult;
}
And your markup is this:
<script src="http://code.jquery.com/jquery-1.10.2.min.js" type="text/javascript"></script>
<asp:RadioButton ID="RadioButtonYes" Text="Yes" runat="server"
Checked="true" GroupName="G"
onclick="MyBtnClick('Yes')"
ClientIDMode="Static"
/>
<asp:RadioButton ID="RadioButtonNo" Text="No" runat="server"
GroupName="G"
onclick="MyBtnClick('No')"
ClientIDMode="Static"
/>
<br />
<h3>Result</h3>
<asp:TextBox ID="TextBox1" runat="server" ClientIDMode="Static"></asp:TextBox>
<script>
function MyBtnClick(sYesNo) {
$.ajax({
type: "POST",
url: "TestAjax.aspx/SyncData",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({data : sYesNo }),
success: function (MyResult) {
$('#TextBox1').val(MyResult.d);
},
failure: function (MyResult) {
alert('error');
}
});
}
</script>
Since ASP run at server control's ID will be generated different ID in client side, so these 2 event handlers binding will not work.
$('#RadioButtonYes').click(function () {...}
$('#RadioButtonNo').click(function () {...}
You could try 2 solutions:
Using control's ClientID for event binding
$('#<%=RadioButtonYes.ClientID%>').click(function () {...}
$('#<%=RadioButtonYes.ClientID%>').click(function () {...}
Adding ClientIDMode="Static" attribute to ASP control
<asp:RadioButton ID="RadioButtonYes" Text="Yes" runat="server" ClientIDMode="Static" Checked="true" GroupName="G" />
<asp:RadioButton ID="RadioButtonNo" Text="No" runat="server" ClientIDMode="Static" GroupName="G" />
** UPDATE:**
Your code also has two more problems:
1 - DataType of your ajax request (json) does not match with response type from server code (text/plain). You could check demo of not matching dataType of ajax request here: https://jsfiddle.net/p2yzLqu1/3/
2 - You were using wrong ajax's callback function failure. We should use done (success) and fail (error) callback functions instead. Please check sample of using done and fail callback at above demo.

Can't insert record into Database without any Postback asp.net

Hi i am having a problem inserting records into database. I am using entity framework as my back end. I have the following code. I am unable to figure out the actual problem in my code since showing no error message when try to run.
.aspx
<link rel="stylesheet" href="/Content/jquery-ui.css" type="text/css" />
<script type="text/javascript" src="/Scripts/1.4.4/jquery.min.js"></script>
<script type="text/javascript" src="/Scripts/1.8.24/jquery-ui.min.js"></script></script>
<script type="text/javascript">
function SaveRecord() {
//Get control's values
var Name = $.trim($('#<%=txtCompanyName.ClientID %>').val());
var msg = "";
//check for validation
if (Name == '') {
msg += "Please enter Name";
}
if (msg.length == 0) {
//Jquery Ajax call to server side method
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "company_master.aspx/InsertCompany",
data: "{'Name':'" + Name + "'}",
success: function (response) {
if (response.d == true) {
$('#lblMsg').text("Saved successfully");
//Clear/Reset controls
$('#txtCompanyName').val('');
//$('#ddlDeptId').val("0");
}
else {
$('#lblMsg').text("Not Saved");
}
},
error: function (xhr, textStatus, error) {
$('#lblMsg').text("Error: " + error);
}
});
}
else {
$('#lblMsg').html('');
$('#lblMsg').html(msg);
}
}
</script>
<div>
<asp:TextBox ID="txtCompanyName" runat="server" placeholder="Enter Company Name" ></asp:TextBox>
<asp:Label ID="lblMsg" runat="server"></asp:Label>
<button type="submit" onclick="SaveRecord()"/>Submit
</div>
C# Code Behind:
using System.Web.Services;
[WebMethod]
public static bool InsertCompany(string Name)
{
bool status = false;
try
{
var company = new CompanyMaster
{
CompanyName = Name
};
using (var context = new DBEntities())
{
context.CompanyMaster.Add(company);
context.SaveChanges();
}
status = true;
}
catch (Exception ex)
{
throw ex;
}
return status;
}
Kindly help me to overcome this problem. Thank you.
No problem your code. can you look in console of chrome?
Request returned 404 or 500.
You can check url :
url: "/company_master.aspx/InsertCompany",
Try this
<button type="button" onclick="SaveRecord(); return false">Submit</button>
Also, check in your browser console, if there's any other error
Try using <input type='button'> and see how that works. There may be a submission conflicting with the event that sends the AJAX request.
I copied your code, and it works without tweaking. The only difference is I have this
<form id="form1" runat="server">
and the div is contained within that. Use default browser as google chrome, and debug using chrome developer tools, it saves time.

RequiredFieldValidator attached to DropDownList does not fire after appending options with jquery

I'm building an ASP.NET page in C#. There are 2 dropdownlists on the page, both have a required field validator. The first ddl is bound from codebehind. The second ddl is populated with a jquery ajax call to a WebMethod based on what was selected in the first ddl.
If I submit the form without selecting any values in either ddl the validators fire as expected. However, when I select a value in the first ddl then select a value in the second ddl and submit the form the Page.IsValid property is false. If I check the validators collection in the Page object and view the validator bound to the second ddl its valid property is false.
I don't know what else to try. I've tried calling ValidatorEnable and ValidatorValidate to try to re-register the validator on the client after selecting a value in the second ddl but it's doesn't work.
Can someone tell me what's going? How do I fix this? I really want to avoid using a postback to populate the second ddl. If anyone has any ideas I'd really appreciate some help.
Here's the code
<asp:RequiredFieldValidator runat="server" ControlToValidate="ddlState" Display="Dynamic" ErrorMessage="Required" InitialValue="" ValidationGroup="County" />
<asp:DropDownList ID="ddlState" runat="server" AutoPostBack="false" ValidationGroup="County" />
<asp:RequiredFieldValidator runat="server" ControlToValidate="ddlCounty" Display="Dynamic" ErrorMessage="Required" InitialValue="" ValidationGroup="County" />
<asp:DropDownList ID="ddlCounty" runat="server" AutoPostBack="false" ValidationGroup="County" />
$('#<%=ddlState.ClientID %>').change(function() {
$('#<%=ddlCounty.ClientID %>').find('option').remove();
var counties = $.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "County.aspx/GetCounties",
data: "{'state':'" + $(this).val() + "'}",
dataType: "json",
dataFilter: function (data) { return data; },
success: function(data) {
var d = jQuery.parseJSON(data.d);
$('#<%=ddlCounty.ClientID %>').append('<option value=""> - select - </option>');
$.each(d, function(i, val){
$('#<%=ddlCounty.ClientID %>').append('<option value="'+ val +'">'+ val +'</option>');
});
},
error: function (jqXHR, error, errorThrown) {
if (jqXHR.status && jqXHR.status == 400) {
alert("An error occurred. Please try again.");
//alert(jqXHR.status + " -- " + jqXHR.responseText);
}
}
});
});
Thanks
My guess would be that the server don't know that the DropDownList have values associated with it. He think they don't have values so don't validate them.
I think you would have to do the same databinding in server code on the selected index changed event of the ddlState.
private void ddlState_SelectedIndexChanged(e as args) : ddlState.SelectedIndexChanged {
// Do your databinding for ddlCountry;
}

Ajax : passing input box value to C# codebehind

I have an AJAX almost working. I can get it to execute a simple function and return a value such as the date and time.
My problem now is developing the script to send the value of an input box to the C# function and then using this value in the code. So that a the correct string can be returned.
If sombody could check if am doing it right or where am going wrong then that would be great
thanks
Ajax Code
$(document).ready(function ste() {
// Add the page method call as an onclick handler for the div.
$("#Result").click(function () {
var thePostCode = $('#ContentPlaceHolder1__postCodeInput').val();
$.ajax({
type: "POST",
url: "Add-Property.aspx/GetAverageRent",
data: { PostCode: thePostCode },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// Replace the div's content with the page method's return.
$("#Result").text(msg.d);
alert("code was executed");
codeAddress();
}
});
});
});
C# Function Code
[WebMethod]
public static string GetAverageRent(string PostCode)
{
string Postcode = PostCode;
var webGet = new HtmlWeb();
var doc = webGet.Load("http://www.webaddress.com" + Postcode);
HtmlNode AvgPrice = doc.DocumentNode.SelectSingleNode("//div[#class='split2r right']//strong[#class='price big']");
if (AvgPrice != null)
{
return AvgPrice.InnerHtml.ToString();
}
else
{
return "Invalid Postcode!";
}
}
Markup
<div class="form-group">
<label for="_postCodeInput">Post Code: </label>
<input type="text" runat="server" id="_postCodeInput" onchange="ste()" class="form-control"/>
<asp:RequiredFieldValidator ID="_pcodeRFV" runat="server" Display="Dynamic" ControlToValidate="_postCodeInput" ValidationGroup="saveProperty" ErrorMessage="Property Postcode" Text="*" ForeColor="Red"></asp:RequiredFieldValidator>
<div id="Result">Click here for the time.</div>

calling function or server controls in webmethod

My html code is
<script type="text/jscript">
function ajaxcall() {
$.ajax({
type: "POST",
url: "index.aspx/lvimgclick",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ }),
dataType: "json",
});
};
</script>
<img src='images/img1.jpg' onclick='return ajaxcall();' /> // calling script
<asp:LinkButton ID="lvlink1" OnClick="lvimg1_Click" CssClass="lv-under" runat="server" >
<asp:Image ID="lvimg1" runat="server" ImageUrl="~/images/spacer.gif" />
<asp:LinkButton ID="lvlink2" OnClick="lvimg2_Click" CssClass="lv-under" runat="server" >
<asp:Image ID="lvimg2" runat="server" ImageUrl="~/images/spacer.gif" />
<asp:LinkButton ID="lvlink3" OnClick="lvimg3_Click" CssClass="lv-under" runat="server" >
<asp:Image ID="lvimg3" runat="server" ImageUrl="~/images/spacer.gif" />
.cs code
[WebMethod]
public static string lvimgclick()
{
return "hi";
}
protected void lvimg1_Click(object sender, EventArgs e)
{
lvlink1.CssClass = "lv-under1";//another class
lvimg1.ImageUrl = "~/images/1.jpg";
lvlink2.CssClass = "lv-under";
lvimg2.ImageUrl = "~/images/spacer.gif";
lvlink3.CssClass = "lv-under";
lvimg3.ImageUrl = "~/images/spacer.gif";
lvlblhd.CssClass = "detailheader";//label
lvlblsubhd.CssClass = "detailsubheader";//label
lvtd.BgColor = "#7e65a9";//td
lvlblhd.Text = "<img src='images/spacer.gif' height='8px' width='5px' /><br/>Wake up";
lvlblsubhd.Text = " to a fragrant day..";
lvlbl.Text = "A beautifully fragrance residence";
}
What I want is :
[WebMethod]
public static string lvimgclick()
{
lvimg1_Click(null, null);
return "hi";
}
or
[WebMethod]
public static void lvimgclick()
{
lvlink1.CssClass = "lv-under1";//another class
lvimg1.ImageUrl = "~/images/1.jpg";
lvlink2.CssClass = "lv-under";
lvimg2.ImageUrl = "~/images/spacer.gif";
lvlink3.CssClass = "lv-under";
lvimg3.ImageUrl = "~/images/spacer.gif";
lvlblhd.CssClass = "detailheader";//label
lvlblsubhd.CssClass = "detailsubheader";//label
lvtd.BgColor = "#7e65a9";//td
lvlblhd.Text = "<img src='images/spacer.gif' height='8px' width='5px' /><br/>Wake up";
lvlblsubhd.Text = " to a fragrant day..";
lvlbl.Text = "A beautifully fragrance residence";
}
what shall I have to do ? I Also have to use lvimg1_Click(null, null); and lvlink1.CssClass = "lv-under1"; at many function which are not to be a webmethod
I am new so please make me know if you want many more information
It can be done only on moment request. You can create server control object in static method and change them, but if you want that changes was apply to client, you need add client code for process string from server response.
So usually you can skip server side method and do all on client at once
UPDATE
If you need only change css class and image url you don't need ajax and web method, all it you can do in client at once like this
<script type="text/jscript">
function imgclick() {
$('#<%= lvlink1.ClientID %>').removeClass().addClass("lv-under1"); //another class
$('#<%= lvimg1.ClientID %>').attr('src','<%= ResolveUrl("~/images/1.jpg") %>');
$('#<%= lvlink2.ClientID %>,#<%= lvlink3.ClientID %>').addClass("lv-under");
$('#<%= lvimg2.ClientID %>, #<%= lvimg3.ClientID %>').attr('src', '<%= ResolveUrl("~/images/spacer.gif") %>');
};
</script>
<img src='images/img1.jpg' onclick='return imgclick();' /> // calling script
<asp:LinkButton ID="lvlink1" OnClick="lvimg1_Click" CssClass="lv-under" runat="server" >
<asp:Image ID="lvimg1" runat="server" ImageUrl="~/images/spacer.gif" />
<asp:LinkButton ID="lvlink2" OnClick="lvimg2_Click" CssClass="lv-under" runat="server" >
<asp:Image ID="lvimg2" runat="server" ImageUrl="~/images/spacer.gif" />
<asp:LinkButton ID="lvlink3" OnClick="lvimg3_Click" CssClass="lv-under" runat="server" >
<asp:Image ID="lvimg3" runat="server" ImageUrl="~/images/spacer.gif" />
if use this case - don't need web methods
UPDATE2
function imgclick() {
...
$('#<%= lvlblhd.ClientID %>').removeClass().addClass("detailheader").html("<img src='images/spacer.gif' height='8px' width='5px' /><br/>Wake up")
$('#<%= lvlblsubhd.ClientID %>').removeClass().addClass("detailsubheader").html(" to a fragrant day..");
$('#<%= lvtd.ClientID %>').css('background-color',"#7e65a9");//td
$('#<%= lvlbl.ClientID %>').text("A beautifully fragrance residence");
...
}
From what i know you can't manipulate server controls with WebMethods, you could use Update Panels if you don't want to do a full postback of the page.
Here is an overview of Update Panels in MSDN : http://msdn.microsoft.com/en-us/library/bb399001.aspx

Categories