Showing posts with label webservice. Show all posts
Showing posts with label webservice. Show all posts

Monday, March 26, 2012

causing validation from client side without postback?

Now that I added callout extenders to my validators how can I get them to work 1- on the client before calling an AJAX webservice and 2- in the webservice? I am not using an update panel so can I turn off server side validation and write my own for the webservice to call?

Hi Echo,

Echo88:

Now that I added callout extenders to my validators how can I get them to work 1- on the client before calling an AJAX webservice and 2- in the webservice? I am not using an update panel so can I turn off server side validation and write my own for the webservice to call?

My understanding of your issue is that you want to validate the inputs. If all these are correct then call the WebService ,otherwise, show the error message by using ValidatorCalloutExtender. If I have misunderstood, please feel free to let me know.

Validators are call before the form is submitted , but to call the WebService we don't need to postback. So I suggest that you should write your own validate Javascript code instead of ValidatorCalloutExtender controls.

Here is the sample to call a WebService.

<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="DataTableService.asmx" InlineScript="true" />
</Services>
</asp:ScriptManager
<input type="button" value="Get DataTable" onclick="getDataTable();" /
<div id="result"></div
<script language="javascript" type="text/javascript">
function getDataTable()
{
DataTableService.GetDataTable(onSucceeded, onFailed);
}

function onSucceeded(result)
{
//handle code
}

function onFailed(error)
{
//handle code
}

You can also transfer all the inputs and validate on the server side in the WebService.

I hope this help.

Best regards,

Jonathan


Thanks - sucks that I can not use those jazzy callouts. But a question I have is - doesn't it call a client script prior to postback?? My understanding is that validation takes place before posting the form data to the server, so one would think there is a call to a script that precedes the actual postback. Am I wrong?


Hi Echo88,

But a question I have is - doesn't it call a client script prior to postback??

Yes , you are right. The problem is that if all the inputs are correct , the form will postback next. But to call a webservice , we usually do not need to postback. It will cause the page refreshment. Based on this , I think write your own Javascript function is a better way in this situation. If you don't want to validate on the client side , you can also transfer all the inputs to the server side and validate on the WebService.

function setBoy()
{
var boy = new Object();
boy.Name = "Terry";
var girl = new Object();
girl.Name = "Mary";
boy.GirlFriend = girl;

BoyGirlService.SetBoyWithGirlFriend(boy, onSetBoySucceeded, onFailed); // call the WebService.
}

I hope this help.

Best regards,

Jonathan


exactly - I am calling a webservice instead of a postback. But am I right to say there should be a way to cause validation on the client - regardless of postback? I just thought there would be a method to execute independently. What aboutPage_ClientValidate() ??


Hi Echo88,

Yes , I agree with you. You can use it like this.

Button1.Attributes["OnClick"] = "Javascript:if (typeof(Page_ClientValidate) == 'function') if(Page_ClientValidate()) {return confirm('Are you sure to submit ?'); } else return false;";

Best regards,

Jonathan


I tried that - no dice. The button is set to cause validation and uses submit behavior. However, nothing is happening? I guess it is not finding Page_ClientValidate function. When include Page_ClientValidate by itself - it throws an error. So why is not included?


Hi Echo88,

Sorry for the delay. Here is my test sample and it works pretty well.

<%@. Page Language="C#" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><script runat="server"> protected void Page_Load(object sender, EventArgs e) { Button1.Attributes["OnClick"] = "Javascript:if (typeof(Page_ClientValidate) == 'function') if(Page_ClientValidate()) {return confirm('Are you sure to submit ?'); } else return false;"; }</script><html xmlns="http://www.w3.org/1999/xhtml" ><head runat="server"> <title>Untitled Page</title></head><body> <form id="form1" runat="server"><%=DateTime.Now.ToString()%> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="RequiredFieldValidator" ControlToValidate="TextBox1"></asp:RequiredFieldValidator> <asp:Button ID="Button1" runat="server" Text="Button" UseSubmitBehavior="true" CausesValidation="true" /> </form></body></html>
So please compare it with yours and if it doesn't work, please feel free to let me know with more information. Thanks.

Best regards,

Jonathan


Your example works - even though it does perform a postback - I turned off the submitbehavior. Still works:) so there is hope- I suspect the

Page_ClientValidate function is not getting generated somehow. Could the fact that I am using them all as part of a user control be the problem?
Thanks - its really appreciated. 

Ok - I found out something interesting... The Page_Validators array is not populating on this one page. Any ideas why they are not populating Page_Validators ?


OK - I found the root of the cause. In my control I have readonly mode that would make all validators invisible if it was in readonly mode. Apparently, I did set the function incorrectly and all validators were not being rendered.

Causing postback

I have written some javascript that async calls a webservice every second. If the service returns true, I want to cause a postback, with client script that can be handled on the server and tell a particular update panel to update in the server side handler.

I also wish to construct event arguments on the client to be passed as part of the post back.

How do I do this?

I need to do something similar, and I'm wondering if you could do it by having your page implement the IPostBackEventHandler. This interface requires that you implement a RaisePostBackEvent method. This method takes a string argument, and you could update your updatepanels in this method. Does anyone know if this approach would work?

Thanks,

Nick


hello.

ipostbackeventhandler is not the answer if you need to update updatepanels. what you could do is:

1. use the postbackaction

2. add a hidden dummy button to the updatepanel and force the submit by calling its click method


Nope, dont need to do that. ipostbackeventhandler is the way to go.

I add some javascript to the page via:

Microsoft.Web.UI.ScriptManager.RegisterClientScriptBlock(
this,
this.GetType(),
"UIService_Agent",
string.Format(
"function CheckAgentTimer()" +
"{{" +
"UIService.ShouldInteruptAgent(OnAgentTimerSucceeded,OnAgentTimerFailure);" +
"}}" +
"function OnAgentTimerSucceeded(result)" +
"{{" +
"if(eval(result))" +
"{{" +
"{0};" +
"}}" +
"setTimeout(\"CheckAgentTimer()\",{1});" +
"}}" +
"function OnAgentTimerFailure()" +
"{{" +
"setTimeout(\"CheckAgentTimer()\",60000);" +
"}}" +
"setTimeout(\"CheckAgentTimer()\",10000);",
this.Page.ClientScript.GetPostBackEventReference(this,AgentTasksTimer.AGENT_PROCESS),
this.timerInterval
),
true);

and then I implement the interface ipostbackeventhandler


public void RaisePostBackEvent(string eventArgument)
{
if (eventArgument == AGENT_PROCESS)
{
//Is There Work for the Agent?
if (WorkItemActionRequired != null && IsWorkItemActionRequired())
{
WorkItemActionRequired(this, new WorkItemEventArgs(ResourceReceiverService.GetUserWork(((IUserPrincipal)Context.User).Credentials.UserId, true)));
}
}
}

Messy I know, but bare with me...

You can then request that update panels are updated on the server i.e. myUpdatePanel.Update

This works!


Luis Abreu:

hello.

ipostbackeventhandler is not the answer if you need to update updatepanels. what you could do is:

1. use the postbackaction

2. add a hidden dummy button to the updatepanel and force the submit by calling its click method

How do you call the click method on a hidden dummy button?


hello.

you must get ?a refernce for the html control and call its click method:

$get("your_button_client_side_id").click();

But will this cause a partial or full post back?

Thanks,

Nick


hello.

it depend: if it's an asp.net button and it's placed inside an updatepanel (or if it's outside the updatepanel but it's configured as a trigger) you'll get a partial postback.

That might do the trick then. Right now I have implemented IPostBackHandler, but it causes a full post-back. I just want to do a partial. How do I make the button invisible, set Visible to false, or set visible to hidden in the button style?

Thanks,

Nick


hello.

it depend: if it's an asp.net button and it's placed inside an updatepanel (or if it's outside the updatepanel but it's configured as a trigger) you'll get a partial postback.
hello again.
well, i'd just add syle="display:none" in the asp.net button declaration.

This will also allow me to put code server-side?

Thanks,

Nick

Saturday, March 24, 2012

CascadingDropDownList?????? :(

My project requirement says we want to use CascadingDropDown, but we dont want to create the webservice. We just want to create a public method .
Any one has an idea of how to do this.

Does any one have the answer?
Any Answers???

CascadingDropDownList - cant handle more than 765 items!

Hello,

My CascadingDropDownList gives me Method 500 error when more than 765 items are returned from the webservice! Is there a way to fix this? Thanks..

Hi,

that's probably related with the limit for the max size of the JSON payload set by ASP.NET AJAX. You can change it in the web.config:

<jsonSerialization maxJsonLength="500" />


this certainly worked! thank you!
Thanks! Helped me alot.
I have tried putting that in every section and it always errors out as unkown element, if someone can help I would really appreciate it!

Hi,

it must be added inside the configuration -> system.web.extensions -> scripting -> webServices section.


Thank you!

Hi,

I have changed the web config maxJsonLength to 1000. But i dont have that many values. First dropdown is giving me a value but on the second dropdown I am getting method error 500. My webservice code is as follows.

Imports

System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Xml

<WebService(Namespace:=

"http://tempuri.org/")> _
<System.Web.Script.Services.ScriptService()> _

Public

Class MIService
Inherits System.Web.Services.WebService
Shared _DocumentAs XmlDocument
Shared _lockAsNewObject
PublicReadOnlyProperty Document()As XmlDocument
Get
If (_DocumentIsNothing)Then
SyncLock _lock
_Document =New XmlDocument
_Document.Load(HttpContext.Current.Server.MapPath("~/App_Data/MIService.xml"))
EndSyncLock
EndIf
Document = _Document
ExitProperty
EndGet
EndProperty
PublicReadOnlyProperty Hierarchy()AsString()
Get
Dim _HeirarchyAsString() = {"city","zip"}
Return _Heirarchy
EndGet
EndProperty
<WebMethod()> _
PublicFunction GetDropDownContents(ByVal knownCategoryValuesAsString,ByVal categoryAsString)As AjaxControlToolkit.CascadingDropDownNameValue()
'Get a dictionary of known category/value pairs
Dim knownCategoryValuesDictionaryAsNew StringDictionary
knownCategoryValuesDictionary = AjaxControlToolkit.CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues)' Perform a simple query against the data document
Return AjaxControlToolkit.CascadingDropDown.QuerySimpleCascadingDropDownDocument(Document, Hierarchy, knownCategoryValuesDictionary, category)
EndFunction
EndClass

My code for aspx file is:

<%

@.PageLanguage="VB"AutoEventWireup="true"CodeFile="Default.aspx.vb"Inherits="_Default"EnableEventValidation="False"%>
<%@.RegisterAssembly="AjaxControlToolkit"Namespace="AjaxControlToolkit"TagPrefix="cc1" %>
<!DOCTYPEhtmlPUBLIC"-//W3C//DTD XHTML 1.1//EN""http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<

htmlxmlns="http://www.w3.org/1999/xhtml">
<headrunat="server">
<title>Untitled Page</title>
<scriptrunat="server">
<System.Web.Services.WebMethod()> _
<System.Web.Script.Services.ScriptMethod()> _
PublicSharedFunction GetDropDownContentsPageMethod(ByVal knownCategoryValuesAsString,ByVal categoryAsString)As AjaxControlToolkit.CascadingDropDownNameValue()
ReturnNew MIService().GetDropDownContents(knownCategoryValues, category)EndFunction
</script>
</head>
<body>
<formid="form1"runat="server">
<asp:ScriptManagerID="ScriptManager1"runat="server"/>
<div>
<asp:UpdatePanelID="UpdatePanel1"runat="server">
<ContentTemplate>
<asp:DropDownListID="DropDownList1"runat="server"Width="200px">
</asp:DropDownList><br/>
<asp:DropDownListID="DropDownList2"runat="server"Width="200px">
</asp:DropDownList><br/>
<asp:DropDownListID="DropDownList3"runat="server"AutoPostBack="True"Width="200px">
</asp:DropDownList><br/>
<br/>
<asp:LabelID="Label1"runat="server"Width="224px"></asp:Label><br/>
<br/>
<cc1:CascadingDropDownID="CascadingDropDown1"runat="server"Category="city"LoadingText="[loading City...]"PromptText="Please select a city."ServiceMethod="GetDropDownContents"ServicePath="MIService.asmx"TargetControlID="DropDownList1"></cc1:CascadingDropDown><cc1:CascadingDropDownID="CascadingDropDown2"runat="server"Category="zip"LoadingText="[Loading Zip...]"ParentControlID="DropDownList1"PromptText="Please enter zip."ServiceMethod="GetDropDownContentPageMethod"TargetControlID="DropDownList2"></cc1:CascadingDropDown><cc1:CascadingDropDownID="CascadingDropDown3"runat="server"Category="county"LoadingText="[loading County..]"ParentControlID="DropDownList2"PromptText="Please select county."ServiceMethod="GetDropDownContents"ServicePath="MIService.asmx"TargetControlID="DropDownList3"></cc1:CascadingDropDown>
<br/>
<br/>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>


Hi,

I have changed the web config maxJsonLength to 1000. But i dont have that many values. First dropdown is giving me a value but on the second dropdown I am getting method error 500. My webservice code is as follows.

Imports

System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Xml

<WebService(Namespace:=

"http://tempuri.org/")> _
<System.Web.Script.Services.ScriptService()> _

Public

Class MIService
Inherits System.Web.Services.WebService
Shared _DocumentAs XmlDocument
Shared _lockAsNewObject
PublicReadOnlyProperty Document()As XmlDocument
Get
If (_DocumentIsNothing)Then
SyncLock _lock
_Document =New XmlDocument
_Document.Load(HttpContext.Current.Server.MapPath("~/App_Data/MIService.xml"))
EndSyncLock
EndIf
Document = _Document
ExitProperty
EndGet
EndProperty
PublicReadOnlyProperty Hierarchy()AsString()
Get
Dim _HeirarchyAsString() = {"city","zip"}
Return _Heirarchy
EndGet
EndProperty
<WebMethod()> _
PublicFunction GetDropDownContents(ByVal knownCategoryValuesAsString,ByVal categoryAsString)As AjaxControlToolkit.CascadingDropDownNameValue()
'Get a dictionary of known category/value pairs
Dim knownCategoryValuesDictionaryAsNew StringDictionary
knownCategoryValuesDictionary = AjaxControlToolkit.CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues)' Perform a simple query against the data document
Return AjaxControlToolkit.CascadingDropDown.QuerySimpleCascadingDropDownDocument(Document, Hierarchy, knownCategoryValuesDictionary, category)
EndFunction
EndClass

My code for aspx file is:

<%

@.PageLanguage="VB"AutoEventWireup="true"CodeFile="Default.aspx.vb"Inherits="_Default"EnableEventValidation="False"%>
<%@.RegisterAssembly="AjaxControlToolkit"Namespace="AjaxControlToolkit"TagPrefix="cc1" %>
<!DOCTYPEhtmlPUBLIC"-//W3C//DTD XHTML 1.1//EN""http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<

htmlxmlns="http://www.w3.org/1999/xhtml">
<headrunat="server">
<title>Untitled Page</title>
<scriptrunat="server">
<System.Web.Services.WebMethod()> _
<System.Web.Script.Services.ScriptMethod()> _
PublicSharedFunction GetDropDownContentsPageMethod(ByVal knownCategoryValuesAsString,ByVal categoryAsString)As AjaxControlToolkit.CascadingDropDownNameValue()
ReturnNew MIService().GetDropDownContents(knownCategoryValues, category)EndFunction
</script>
</head>
<body>
<formid="form1"runat="server">
<asp:ScriptManagerID="ScriptManager1"runat="server"/>
<div>
<asp:UpdatePanelID="UpdatePanel1"runat="server">
<ContentTemplate>
<asp:DropDownListID="DropDownList1"runat="server"Width="200px">
</asp:DropDownList><br/>
<asp:DropDownListID="DropDownList2"runat="server"Width="200px">
</asp:DropDownList><br/>
<asp:DropDownListID="DropDownList3"runat="server"AutoPostBack="True"Width="200px">
</asp:DropDownList><br/>
<br/>
<asp:LabelID="Label1"runat="server"Width="224px"></asp:Label><br/>
<br/>
<cc1:CascadingDropDownID="CascadingDropDown1"runat="server"Category="city"LoadingText="[loading City...]"PromptText="Please select a city."ServiceMethod="GetDropDownContents"ServicePath="MIService.asmx"TargetControlID="DropDownList1"></cc1:CascadingDropDown><cc1:CascadingDropDownID="CascadingDropDown2"runat="server"Category="zip"LoadingText="[Loading Zip...]"ParentControlID="DropDownList1"PromptText="Please enter zip."ServiceMethod="GetDropDownContentPageMethod"TargetControlID="DropDownList2"></cc1:CascadingDropDown><cc1:CascadingDropDownID="CascadingDropDown3"runat="server"Category="county"LoadingText="[loading County..]"ParentControlID="DropDownList2"PromptText="Please select county."ServiceMethod="GetDropDownContents"ServicePath="MIService.asmx"TargetControlID="DropDownList3"></cc1:CascadingDropDown>
<br/>
<br/>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>

Thank You,

Nepalaya


Hi,

what's the content of the 500? You can useFiddler to examine it.


I hope u get it the way you want, but 765 items in a drop down list isn't very user friendly? Think about screen res?

Maybe test out autocomplete control?

Just giving my view, but if you want 1000 items in a drop down list, go for it :P (I know how annoying it is when people try to divert you from the solution you want, so go for what is best in your app, just throwing out a suggestion)


Hi,

The problem resolved. It was not related with the lenght. Page method was not working so change the service method name to GetDropDownContents and it works.

<

cc1:CascadingDropDownID="CascadingDropDown1"runat="server"Category="city"LoadingText="[loading City...]"PromptText="Please select a city."ServiceMethod="GetDropDownContents"ServicePath="MIService.asmx"TargetControlID="DropDownList1">
</cc1:CascadingDropDown><cc1:CascadingDropDownID="CascadingDropDown2"runat="server"Category="zip"LoadingText="[Loading Zip...]"ParentControlID="DropDownList1"PromptText="Please enter zip."ServicePath="MIService.asmx"ServiceMethod="GetDropDownContents"TargetControlID="DropDownList2">
</cc1:CascadingDropDown>

Thanks,

Nepalaya


Hello freinds,

I am not able to fill the cascading drop down using database. Does any one have fill it with the database??

Please help me i am stuck with this problem.

Thaks in advance.


Hi,

I get method error 500 in dropdownlist1 . Iam using WEB SERVICE .

i used <jsonSerializationmaxJsonLength="500" /> in web.config but still i get the error.

Can any one help ?

Thanks

Cascadingdropdown with database

I was reading about cascadingdropdown and i see an example to work with a database with webservice but my application architecture don`t permit do that. i have to call another class first. well there an example of cascadingdropdown to call a metod on the page in place webservice?

regardsThe CascadingDropDown sample page that comes with the Toolkit shows how to use it with both a web service and a page method.

CascadingDropDown with a Database, Method Error 405

Hey guys,


I followed the AjaxControlToolki tinstructions on how to create a WebService and specify everything so that it would populate two DropDownLists. The problem is, the first DropDownList has a [Method Error 405] as its only value. If I select it, the second DropDownList is populated with the same.

After checking, rechecking and extensively searching, I haven't found my error. I've read at least a dozen topics on this error but none have helped me.

Here is my code:

App_Code/StateServices.cs:

using System;
using System.Web;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Web.Services;
using System.Web.Services.Protocols;
using AjaxControlToolkit;
using System.Data;

/// <summary>
/// Summary description for StateServices
/// </summary>[WebService(Namespace ="http://tempuri.org/")][WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)][System.Web.Script.Services.ScriptService]public class StateServices : System.Web.Services.WebService { GeographicalDelimitationsDB GeoDataSource = new GeographicalDelimitationsDB(); GeographicalDelimitationsDBTableAdapters.CountyInfoTableAdapter GeoCountyInfoTableAdapter = new GeographicalDelimitationsDBTableAdapters.CountyInfoTableAdapter(); GeographicalDelimitationsDBTableAdapters.ZipCodesTableAdapter GeoZipCodesTableAdapter = new GeographicalDelimitationsDBTableAdapters.ZipCodesTableAdapter(); public StateServices() { } [WebMethod] public CascadingDropDownNameValue[] GetCounties(string knownCategoryValues, string category) { GeographicalDelimitationsDB.CountyInfoDataTable counties = GeoCountyInfoTableAdapter.GetData(); List<CascadingDropDownNameValue> values = new List<CascadingDropDownNameValue>(); foreach (DataRow dr in counties.Rows) { string name = (string)dr["Name"];
int countyID = (int)dr["CountyCode"];

values.Add(new CascadingDropDownNameValue(name, countyID.ToString()));
}

return values.ToArray();
}

[WebMethod]
public CascadingDropDownNameValue[] GetCitiesForCounty(string knownCategoryValues, string category)
{
StringDictionary kv = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);

int countyID;

if (!kv.ContainsKey("County") || !Int32.TryParse(kv["County"], out countyID))
{
return null;
}

GeographicalDelimitationsDB.ZipCodesDataTable cities = GeoZipCodesTableAdapter.GetDataByCountyID(countyID);

List<CascadingDropDownNameValue> values = new List<CascadingDropDownNameValue>();

foreach (DataRow dr in cities.Rows)
{
values.Add(new CascadingDropDownNameValue((string)dr["City"], dr["ZIP"].ToString()));
}

return values.ToArray();
}
}

 
index.aspx: 

 <asp:UpdatePanel ID="NavigationUpdatePanel" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Panel ID="ConfigurationContentPart" runat="server" CssClass="module-content">
<h3>County:</h3>
<p>
<asp:DropDownList ID="CountyList" runat="server" onchange="selectCounty(this)" />
</p>
<h3>City:</h3>
<p>
<asp:DropDownList ID="CityList" runat="server" onchange="selectCity(this)" />
</p>
</asp:Panel
<ajaxToolkit:CascadingDropDown ID="CountyCascadingDropDown" runat="server" TargetControlID="CountyList" Category="County" PromptText="Select a County" LoadingText="[Loading...]" ServicePath="StateServices.asmx" ServiceMethod="GetCounties" />
<ajaxToolkit:CascadingDropDown ID="CityCascadingDropDown" runat="server" TargetControlID="CityList" Category="City" PromptText="Select a City" LoadingText="[Loading...]" ServicePath="StateServices.asmx" ServiceMethod="GetCitiesForCounty" ParentControlID="CountyList" /
</ContentTemplate>
</asp:UpdatePanel>
</asp:Panel>

Bump...

Please help, I'm really stuck!


Does it work without the onchange handlers on the DropDownLists?

Wednesday, March 21, 2012

CascadingDropDown items limited (Error) ??

Hello people,

I have a big problem with CDD, try to load a large amount of items, for example.

In the sample of CDD change the webservice "CarsService" method "GetDropDownContents",
insert this code:

for (int i = 0; i < 870; i++)
{
values.Add(new CascadingDropDownNameValue(string.Format("Name{0}",i), string.Format("Value{0}",i)));
}

and the Method Erro 500 show ...

my list are 890 items

Please Help...!Idea

What is the exact error you are getting? Is it possible to figure out at what exact number of items cdd starts to error out?

Also, what is the scenario in which you need to have so many items in a cdd? From a usability point of view it does not seem very appropriate.


Try:http://ajax.asp.net/docs/mref/P_System_Web_Script_Serialization_JavaScriptSerializer_MaxJsonLength.aspx

Thank you so much for your response...

Solve my problem perfect...Yes

Big Smile