How to know server response in ResponseEnd method of a RadAjaxManager - asp.net

Im using Rad ajax manager, RadAjaxLoadingPanel in my webform.
I have two panels in my form, Panel1 is having Create account controls and another Panel2 is for Thank you notes.
When user created an account successfully i need to hide Panel 1 and show Panel 2.
Im using ResponseEnd method to do make visible/hide using Javascript below method.
function ResponseEnd(sender, arguments) {
//hide the loading panel and clean up the global variables
if (currentLoadingPanel != null) {
currentLoadingPanel.hide(currentUpdatedControl);
}
ShowTY();
currentUpdatedControl = null;
currentLoadingPanel = null;
}
function ShowTY(){
document.getElementById('<%= Panelty.ClientID %>').style.visibility = "visible";
document.getElementById('<%= Panelty.ClientID %>').style.display = "block";
document.getElementById('<%= Panelsu.ClientID %>').style.visibility = "false";
document.getElementById('<%= Panelsu.ClientID %>').style.display = "none";
}
If user already exist or any db server error i need show Panel1 display error message in a Label
For this I need to write a condition to check whether server response succeeded or not in the above method.
Please let me know how i can know the server response or how i can handle this issue.....
Please reply soon
Thanks

According to the documentation: There is no way to pass data from an event on the server to the client side event handler.
I would suggest moving the logic to configure the display (hiding/showing elements, displaying error messages) to the server, where the code to create the account is. Since you are using the loading panels, this should be straightforward:
if(accountCreatedSuccessfully) {
Panelty.Visible = true;
Panelsu.Visible = false;
}
else {
// TODO: display the error messages somewhere, in a label
Panelty.Visible = false;
Panelsu.Visible = true;
}

Related

Activity Indicator is not visible on xaml page in xamarin.forms?

I have an activity indicator on xaml page. Initially its IsVisible property is false. I have a button on page. When user click on button it calls a web service to get data. I change the value of IsVisible property to true before calling the service so that activity indicator starts to display on page and after successful calling of service I change its value to again false so that it doesn't show any more on page.
But it is not working. I know the actual problem. When we call the web service the UI thread gets block and it doesn't show the activity indicator.
How I can enable the UI thread when web service gets called so that activity indicator can show on page until we get the data?
Try making your webservice call into an async and await it.
Depending on how you've structured things you may have to use a TaskCompletionSource as the following example demonstrates.
In this example when the button is clicked, the button is made invisible, and the ActivityIndicator is set to IsRunning=True to show it.
It then executes your long running task / webservice in the function ExecuteSomeLongTask using a TaskCompletionSource.
The reason for this is that in our button click code, we have the final lines:-
objActivityIndicator1.IsRunning = false;
objButton1.IsVisible = true;
That stop the ActivityIndicator from running and showing, and also set the button back to a visible state.
If we did not use a TaskCompletionSource these lines would execute immediately after calling the ExecuteSomeLongTask if it was a normal async method / function, and would result in the ActivityIndicator not running and the button still being visible.
Example:-
Grid objGrid = new Grid()
{
};
ActivityIndicator objActivityIndicator1 = new ActivityIndicator();
objGrid.Children.Add(objActivityIndicator1);
Button objButton1 = new Button();
objButton1.Text = "Execute webservice call.";
objButton1.Clicked += (async (o2, e2) =>
{
objButton1.IsVisible = false;
objActivityIndicator1.IsRunning = true;
//
bool blnResult = await ExecuteSomeLongTask();
//
objActivityIndicator1.IsRunning = false;
objButton1.IsVisible = true;
});
objGrid.Children.Add(objButton1);
return objGrid;
Supporting function:-
private Task<bool> ExecuteSomeLongTask()
{
TaskCompletionSource<bool> objTaskCompletionSource1 = new TaskCompletionSource<bool>();
//
Xamarin.Forms.Device.StartTimer(new TimeSpan(0, 0, 5), new Func<bool>(() =>
{
objTaskCompletionSource1.SetResult(true);
//
return false;
}));
//
return objTaskCompletionSource1.Task;
}
You need to do your work in an asynchronous way. Or in other words: Use Asnyc & Await to ensure, that you UI works well during the call.
You can find more informations in the Xamarin Docs.
async and await are new C# language features that work in conjunction
with the Task Parallel Library to make it easy to write threaded code
to perform long-running tasks without blocking the main thread of your
application.
If you need further asistance, please update your question and post your code or what you have tried so far.

Ajax code is faster or updatepanel is faster to populate dropdown in asp.net

I have 20 ajax editable drop-downs in a form. Each drop-down binds with respect to other's selectedindex change.
I have lots of record coming from the database for binding, and some operations. What will perform better?
Should I use this code to bind the drop-down:
var XmlHttp;
//Creating object of XMLHTTP For AJAX Method
function CreateXmlHttp() {
//Creating object of XMLHTTP in IE
try {
XmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
XmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (oc) {
XmlHttp = null;
}
}
//Creating object of XMLHTTP in Mozilla and Safari
if (!XmlHttp && typeof XMLHttpRequest != "undefined") {
XmlHttp = new XMLHttpRequest();
}
}
function GetAppStoreLnk(id) {
var txtnameid = document.getElementById(id);
CreateXmlHttp();
var requestUrl = "Default2.aspx?id="+txtnameid+"";
if (XmlHttp) {
XmlHttp.onreadystatechange = function() { getschemename(txtnameid) };
XmlHttp.open("GET", requestUrl, true);
XmlHttp.send(null);
}
}
function getschemename(id)
{
// To make sure receiving response data from server is completed
if(XmlHttp.readyState == 4) {
// To make sure valid response is received from the server, 200 means response received is OK
if(XmlHttp.status == 200) {
var strData = XmlHttp.responseText;
if(strData != "") {
var arrscheme = strData.split("|");
id.length = 0;
for(i=0; i<arrscheme.length-1; i++) {
var strscheme = arrscheme[i];
var arrschnm = strscheme.split("~");
id.options[i] = new Option();
id.options[i].value = arrschnm[0];
id.options[i].text = arrschnm[1];
}
} else {
id.length = 0;
id.options[0] = new Option();
id.options[0].value = "";
id.options[0].text = "Scheme Name is not available";
}
document.body.style.cursor = "auto";
}
else {
id.length = 0;
id.options[0] = new Option();
id.options[0].value = "";
id.options[0].text = "server is not ready";
document.body.style.cursor = "auto";
}
}
}
Or should I go for UpdatePanel?
Which one will be the better option for me?
Or is there a better spolution?
I want very good performance as this page is used frequently by our client, and we want to make sure it is fast.
I am using vs2010.
The AJAX route will be faster. UpdatePanels make things look like partial page loads, but in fact, it returns the whole page and just updates the section inside your UpdatePanel.
UpdatePanel does not provide the efficiency that we normally associate with AJAX. Did you know, for example, that when UpdatePanel control performs asynchronous AJAX callback to the server to update its content, the request contains all the content of a publication automatically ASP. NET conventional, including status display.
An application is more effective preferring to use asynchronous calls to WebMethods or page methods instead of using UpdatePanel.
Link : http://msdn.microsoft.com/fr-fr/magazine/cc163413.aspx
I agree with the rest of the answers, the evil UpdatePanel decreases the overall performance of the page because in order to work, it must send the whole page ViewState back and forth in order to execute the whole page life cycle on every async post
With simple AJAX calls this is totally different, the calls only get the data you need and the performance is considerably better
However - danger danger DR Robinson
Since you are using WebForms and your intention is to populate 20 DropDownLists, you can try doing it with AJAX calls and you will notice that apparently that works correctly. but if you try to post your page with one value added to a DropDownList via javascript/jquery, an exception will be thrown.
This is because ASP.Net WebForms by default validates the values posted to the server, if the values are not registered in the ViewState, a security exception will be thrown because of an attempt to tamper the page content.
Sadly you cannot disable this option at control level, you would have to disable it at page level:
<%# Page EnableEventValidation="false" ....
In WebForms this is not recommended though...

ASP.Net Drop Down List not passing a value when updated using ajax

I have some jQuery that I'm using to open a pop-up window where a new consignor can be added to the database. The original window has a dropdownlist of all of the current consignors. When you add the new consignor in the pop-up window, that window closes and the original window then reloads the dropdownlist's data and selects the one just created.
All of that works perfectly. My issue is that when you fill out the rest of the form and submit it, it passes an empty string instead of the value of the selected item. Is this because it's an ASP.Net script? I don't know a lot about ASP.Net, but I've never had this issue with PHP. Can someone explain how I would go about refreshing the dropdownlist without refreshing the entire page and still get the list to pass it's value upon form submission?
My javascript code on the page that opens the pop-up and reloads the list is below:
function openConsignorAdd() {
var url;
url = "/admin/consignor/csAdd.aspx";
window.open(url, "WizardWindow", "width=400,height=500,resizable=yes,scrollbars=yes");
}
function loadNewAdded(fn, cs_txt_id) {
// var pagePath = window.location.pathname;
var pagePath = "/admin/getNewList.asp";
var paramList = "data=";
//Call the page method
$.ajax({
type: "POST",
url: pagePath + "?type=" + fn + "&cs_txt_id=" + cs_txt_id,
data: paramList,
success: function (data) {
//create jquery object from the response html
var $response = $(data);
//query the jq object for the values
var results = $response.filter('select#results').html();
if (fn == "consignor") {
$("select#<%=itemConsigner.ClientID%>").html(results);
} else if (fn == "cdr") {
$("select#<%=itemCDR.ClientID%>").html(results);
}
},
error: function () {
alert("Failed To Refresh!\n\nYou must manually refresh the page.");
}
});
}
My javascript code on the pop-up page to refresh the list is:
function refreshOpener(cs_txt_id) {
window.opener.loadNewAdded("consignor", cs_txt_id);
}
Those both work. And to get the value of my dropdownlist, I simply use:
if (itemConsigner.SelectedValue.ToString() != string.Empty)
{
itemCsTxtId = itemConsigner.SelectedValue.ToString();
}
with my dropdownlist being:
<asp:DropDownList ID="itemConsigner" runat="server" TabIndex="1"></asp:DropDownList>
If you need more info, just let me know. Any help is appreciated.
It seems that the issue is that since I am making the change after the page loads, the server does not see my new addition as one of the original options so ignores it completely. This is good so that people cannot just edit your forms I guess. So what I did was instead of getting the value of itemConsigner.SelectedValue, I grab the value for Request.Form["itemConsigner"] with the long ID. That way it doesn't validate that my submitted option was an original option.
Might be a silly observation but without all the code I'm not sure if this is the case. Are you just updating the original list with the id in the select options. The value needs to be populated as well for each. That could be why you are getting an empty value on after form submission.

How to display save confirmation message on my Web form when user saves new form by clicking Save button

I am very new to ASP.NET. I am working on some other developer's Web form. I have been asked to fix a bug which says:
No success message is displayed when user clicks Save button after
adding information to the form (first time or while updating)
There is a Label at the top of the page with ID lblMsgs
<asp:Label ID="lblMsgs" runat="server">
I have added this to the Code behind in the appropriate place:
lblMsgs.Text = "Message Text";
Now, my question is how do I modify the HTML or code behind to make sure that when Save button is clicked, the code checks that the data is saved to the database and displays save successful message on the Web form.
Can you please help by giving example of the code using my label ID above?
Thank you in advance.
That's a pretty vague question, but if your looking for data validation you should look at the built in ASP.NET Validators. This can do client/server side data validation. As for returning a message to the user based on a successful update to the DB, that is going to be solution specific depending on what type of data layer your using.
On your Save button handler, you can add validation logic if whether the data is valid or not.
protected void ValidateSave(object o, EventArgs e){
if (Page.IsValid) {
// Save to DB and notify of update status
var success = SomeDBMethod.Update...
if (success){
DoAlert("Saved Successfully!");
}
}
else { lblMsgs.Text = "Failed"; }
}
// Call client-side alert
private void DoAlert(string message) {
ClientScriptManager cs = Page.ClientScript;
var x = "alertScript";
if (!cs.IsStartupScriptRegistered(cstype, x))
{
String script = string.Format"alert('{0}', message);";
cs.RegisterStartupScript(cstype, x, script, true);
}
}

ASP.NET session in Javascript

I have the following code invoked from a button click - js event
function onOkReason() {
alert("called");
var session = $('<%=Session["A"]%>');
if (session == null) {
<%Session["A"]%> = "1";
alert("1");
}
else {
<%Session["A"]%> = null;
alert("2");
}
alert(session);
}
It does not seem to work...Any pointers as to what may be wrong...
The <% %> is evaluated when the page is processed on the server, you can't then set it from the client - it's to late, the page has been processed and sent back to the clients browser.
You'll need to post back to the server (either full or an AJAX call) to set the data.

Resources