ラベル user の投稿を表示しています。 すべての投稿を表示
ラベル user の投稿を表示しています。 すべての投稿を表示

2012年3月28日水曜日

Reset controls in update panel when error is thrown

Hello fellow developers,

A user enters a value in a textbox and i click a button to get some data, but a server error is thrown.

Is there a way to clear/reset the textbox in an UpdatePanel when there is a server error?

If there is a way, can someone assist in providing me that trick?

Thanks in Advance.

Protected Sub myButton_Click(ByVal senderAs Object,ByVal eAs System.EventArgs)Handles myButton.Click
Try
' Whatever code that I'm trying to run goes here.
' This is the code that my produce the error.
Catch
myTextbox.Text =""
End Try
End Sub


Can't you simply use a try/catch block, and catch the exception? If an exception is thrown reset it to the old value. You can use a hidden label or textbox to store the previous value.


Use this

protected void ScriptManager1_AsyncPostBackError(object sender, AsyncPostBackErrorEventArgs e)
{
if (condition)
{
ScriptManager1.AsyncPostBackErrorMessage =
e.Exception.Message;

}
else
{
ScriptManager1.AsyncPostBackErrorMessage =
"An unspecified error occurred.";
}
}


I apologize. My example scenario was not explained the way I originally thought.

The example should be that when using AJAX you want to show an error message AND reset the controls.

If you write code to 'Throw' a custom error message to an alert window, nothing after the 'Throw' gets executed (clearing my textbox).

So my question really should be:

Is there a way, using AJAX, to 'Throw' a custom error message to an alert window and still reset controls? Either on the server or client side.

Thanks.


Protected Sub myButton_Click(ByVal senderAs Object,ByVal eAs System.EventArgs)Handles myButton.Click
Try
' Whatever code that I'm trying to run goes here.
' This is the code that my produce the error.
Catch exAs Exception
ScriptManager.RegisterStartupScript(Page, Page.GetType,"ErrorMsg", "alert('" & ex.Message & "');",True)
myTextbox.Text =""
End Try
End Sub


Thanks Buddha, that's just what I needed.

ResizableControlExtender Handle Click Event

I would like to be able to fire the event that occurs when the user clicks on the handle

ResizableControlExtender from my own javascript code.

Do you know how to do this?

Your help is much appreciated.

Thak you very much

Hi,

Internally, this extender doesn't support such behavior.

You may add an resizebegin event handler to the extender, in this handler, call a asynchronous method to invoke to method on server side( web service or pageMethod ) .

So, you code may goes like this:

function pageLoad()

{

var re = $find("behaviorID of the resizableExtender");

re.add_resizebegin(onResizeBegin);

}

function onResizeBegin()

{

//invoke a service side method here.

}

Hope this helps.

Resizing a panel using Animation Extender

Hi Everyone,

I have 3 rows of images on my form and each row has 3 images as well. I want to have a effect so that when the user hovers on a row than that row expands itself and the rest of the rows remain the same size.

To do this I used 3 panels and in each panel I inseted a table so as to accomodate the 3 images.

Then to add the Hover effect I used the Animation extender control. The code that I used is given below.

<cc1:AnimationExtenderID="AnimationExtender1"runat="server"TargetControlID="Panel1">

<Animations>

<OnHoverOver>

<ParallelDuration=".1"fps="50">

<ResizeWidth="250"Height="260" />

</Parallel>

</OnHoverOver>

</Animations>

</cc1:AnimationExtender>

However this doesn't seem to work. Any idea about why this is happening. It seems to me that I am making a really basic mistake but I have been trying to make this work for quite some days with no success.

If anyone has any idea what the problem is here please let me know.

Thanks

Hi,

I created a sample that works fine according to your description, please try it:

<%@. 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"></script><html xmlns="http://www.w3.org/1999/xhtml" ><head runat="server"> <title>Untitled Page</title></head><body> <form id="form1" runat="server"> <div> <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> <table> <tr> <td> <asp:Image ID="Image1" runat="server" ImageUrl="~/Images/Add.gif" Height="50" Width="50"/> <ajaxtoolkit:AnimationExtender ID="AnimationExtender1" runat="server" TargetControlID="Image1"> <Animations> <OnHoverOver> <Parallel Duration=".1" fps="50"> <Resize Width="250" Height="250" /> </Parallel> </OnHoverOver> <OnHoverOut> <Parallel Duration=".1" fps="50"> <Resize Width="50" Height="50" /> </Parallel> </OnHoverOut> </Animations> </ajaxtoolkit:AnimationExtender> </td> <td> <asp:Image ID="Image2" runat="server" ImageUrl="~/Images/edit.gif" Height="50" Width="50"/> <ajaxtoolkit:AnimationExtender ID="AnimationExtender2" runat="server" TargetControlID="Image2"> <Animations> <OnHoverOver> <Parallel Duration=".1" fps="50"> <Resize Width="250" Height="250" /> </Parallel> </OnHoverOver> <OnHoverOut> <Parallel Duration=".1" fps="50"> <Resize Width="50" Height="50" /> </Parallel> </OnHoverOut> </Animations> </ajaxtoolkit:AnimationExtender> </td> <td> <asp:Image ID="Image3" runat="server" ImageUrl="~/Images/delete.gif" Height="50" Width="50"/> <ajaxtoolkit:AnimationExtender ID="AnimationExtender3" runat="server" TargetControlID="Image3"> <Animations> <OnHoverOver> <Parallel Duration=".1" fps="50"> <Resize Width="250" Height="250" /> </Parallel> </OnHoverOver> <OnHoverOut> <Parallel Duration=".1" fps="50"> <Resize Width="50" Height="50" /> </Parallel> </OnHoverOut> </Animations> </ajaxtoolkit:AnimationExtender> </td> </tr> <tr> <td> </td> <td> </td> <td> </td> </tr> <tr> <td> </td> <td> </td> <td> </td> </tr> </table> </div> </form></body></html>

Thanks Raymond that surely helps....

However I have another problem and it will be great if you can have a look at that also....

http://forums.asp.net/p/1168745/1950736.aspx#1950736

Thanks in advance

vishy

Response.redirect - display text in same page.

Hi guys,

I am using A.aspx , B.aspx and C.aspx pages.

From A.aspx I am calling b.aspx via Ajax code. After (Check Login user from database) success status , I am tryint o redirecting to C.aspx. But

C. aspx page content is dispalying in A.aspx. It suppose to be redirec to C.aspx. What I am dong wrong here..??

any suggessions ??

hello.

well, i'mo not following you. can you be more specific?


I am trying to check the Loginuser permissions from the Database. Once he get success permission the page has to redirect to new page.
here is my Code.

Login.aspx (a.aspx) - Enter user id & pwd and click Submit then below code executes


function CheckUser()
{
if (preLoginCheck())
{ var url = serverName+"checkLogUser.aspx?userID="+ document.frmDefault.txtUid.value +"&Pwd="+ document.frmDefault.txtPwd.value;
xmlHttp = GetXmlHttpObject(ChangeHandler);
xmlHttp_Get(xmlHttp, url);
}
}


function ChangeHandler()
{ if (xmlHttp.readyState == 4 || xmlHttp.readyState == 'complete')
{ var getData=xmlHttp.responseText;
if (getData=="Success")
{ document.getElementById("ErrorCode").innerText=" GoooooooooooooooD";
}
else
{
document.getElementById("ErrorCode").innerText=getData; //" Invalid User name /Password";
}
}
}

checkLogUser.aspx (b.aspx) - Ajax will execute this page from here itself I want to redirec to Third Page..


If (tmpUserID <> "" And tmpUserPwd <> "") Then
crapObj = New CRAPManagement
getLogInStatus = crapObj.checkLoginUserAccess(tmpUserID, tmpUserPwd)
If getLogInStatus = "Success" Then
Response.Redirect("UserCreate.aspx") --> C.Aspx
Else
Response.Write(getLogInStatus)
End If
End If

Finanl result is C.Aspx page content is displaed in Login.aspx Page.


hello.

well, if you're using asp.net 2.0, then check the authenticationservice class:

http://www.asp.net/ajax/documentation/live/ClientReference/Sys.Services/AuthenticationServiceClass/default.aspx


Hello,
I could't understand wha should I do exactly...!


hello.

well, instead of writing your own code for making the remote call and then having to build your page on the server that has server logic for authenticating a user, you'll get that for free with the service i've showed you in the previous post (it'll authenticate by using forms authentication and it'll automatically use the current defined membership provider you've set up on the server side).

Response.Redirect and AsyncPostBackTrigger

I've got a "Previous" button on a webform that uses this code to take user to previous page:

Response.Redirect(Session.Item("PREVIOUSPAGE"))

I set the button as an AsyncPostBackTrigger. This error occurs when the button is clicked:

Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed.

If I change the button from AsyncPostBackTrigger to PostBackTrigger, it works fine.

Why won't this button work asynchronously? I've got 2 other buttons on the same page that are being used as AsyncPostBackTriggers with no issue.


I think it would not work because asynchronously - the Ajax enviroment is just expecting to work with the session variables of the current page, but you are trying to tell it to revert back to previous session ids with a redirect. A postback will work because it reloads or mimics a back button of the browser. Not saying it is not possible - I am wrong plenty of times - but it would make sense that that would be the behavior. You'll also get the same behavior if a session times out and the user tries to do a back button to a previous ajax enabled page.

What I would at least consider a better solution is leverage the ability with Ajax to load and unload controls dynamically. This way you can have 'paging' and still retain the benefits of the asyncrhonous enviroment.


There is an article on how to achieve that in the Scott Guthrie's blog:


http://weblogs.asp.net/scottgu/archive/2007/02/06/asp-net-ajax-goodies-documentation-download-back-button-support-new-animation-control.aspx

Juan

2012年3月26日月曜日

Response.redirect causes post back using Atlas


Hi,

I have a webpage with a button on it. The button is placed in an update panel. I want to redirect user to another page when the user press the button. Basically it is a save button which save user information and redirect user to another page.

I tried using response.redirect("anotherpage.aspx") but it caused post back however the button is placed under a n update panel.

Can anyone help me out? I want to save data on button click and redirect user to another page without causing post back.


Thanks.
Imtiaz

Redirect has to cause a postback, you are trying to "redirect" the user.

Firstly, all things inside an update panel cause a postback, they just go through some different steps, and only deal with events in the update panel, and only refresh the part of the page inside the panel.

So your button is designed to postback, which it does... then redirects, the update panel picks this up, and changes the browser page.

The functionality is correct.

If you want, instead of a button with a redirect, make a regular html button with a clientside event.

onclick="redirect();"

function redirect(){

location.herf = 'newURL.aspx';

}

If you call a client side method to change the location of the page, then there is no post back to the server

Response.Redirect not working while inside an Update Panel

I have a link button inside an update panel. When the user clicks this button, it calls a function that performs a database update and then redirects them to another page. However, Response.Redirect isn't working with AJAX. Any suggestions how I can do this? Thanks!Can you post your code here?

Hi,

Reponse.Redirect works with UpdatePanel. Please refer to this sample:

<%@. 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 Button1_Click(object sender, EventArgs e) { Response.Redirect("http://www.microsoft.com"); }</script><html xmlns="http://www.w3.org/1999/xhtml" ><head runat="server"> <title>Untitled Page</title></head><body> <form id="form1" runat="server"> <div> <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> </div> <asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate> <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" /> </ContentTemplate> </asp:UpdatePanel> </form></body></html>

Restricting Dates in an AJAX Calendar

I need to build some logic into my ajax calendar control to prevent the user from entering a date that is less than today's date. I have two text boxes with one called SDate and another called FDate. Each of these text boxes have AJAX calendar extenders attached. So i am trying to figure out when the user clicks the text box, they can only select a date from the AJAX calendar that occurs from today's date onwards. The previous dates should be unselectable.

I thought the follwing code would work, but it seems it does not, as the AJAX calendar control doesn't seem to have the DayRender feature of the full .NET calendar.

ProtectedSub CEStartDate_DayRender(ByVal senderAsObject,ByVal eAs DayRenderEventArgs)

If e.Day.[Date] < Today()Then

e.Day.IsSelectable =False

Else

e.Day.IsSelectable =True

EndIf

EndSub

Any thoughts??

Hi Lochview,

Yes , we can keep the select date in within boundies when we use Calendar but not CalendarExtender(Ajax control). Based on the research of its source code, we can find that CalendarExtender generated all on the client using Javascript and we can control less on the server side. So unfortunately, we cannot achieve what you want by using any direct properties or functions unless we modify its source code. Below is the code snippet which is used to generate its days.

_buildDays : function() {
/// <summary>
/// Builds a "days of the month" view for the calendar
/// </summary>

var dtf = Sys.CultureInfo.CurrentCulture.dateTimeFormat;

this._days = $common.createElementFromTemplate({
nodeName : "div",
cssClasses : [ "ajax__calendar_days" ]
}, this._body);
this._modes["days"] = this._days;

this._daysTable = $common.createElementFromTemplate({
nodeName : "table",
properties : {
cellPadding : 0,
cellSpacing : 0,
border : 0,
style : { margin : "auto" }
}
}, this._days);

this._daysTableHeader = $common.createElementFromTemplate({ nodeName : "thead" }, this._daysTable);
this._daysTableHeaderRow = $common.createElementFromTemplate({ nodeName : "tr" }, this._daysTableHeader);
this._daysBody = $common.createElementFromTemplate({ nodeName: "tbody" }, this._daysTable);

for (var i = 0; i < 7; i++) {
var dayCell = $common.createElementFromTemplate({ nodeName : "td" }, this._daysTableHeaderRow);
var dayDiv = $common.createElementFromTemplate({
nodeName : "div",
cssClasses : [ "ajax__calendar_dayname" ]
}, dayCell);
}

for (var i = 0; i < 6; i++) {
var daysRow = $common.createElementFromTemplate({ nodeName : "tr" }, this._daysBody);
for(var j = 0; j < 7; j++) {
var dayCell = $common.createElementFromTemplate({ nodeName : "td" }, daysRow);
var dayDiv = $common.createElementFromTemplate({
nodeName : "div",
properties : {
mode : "day",
innerHTML : " "
},
events : this._cell$delegates,
cssClasses : [ "ajax__calendar_day" ]
}, dayCell);
}
}
}

I hope this help.

Best regards,

Jonathan.

Restricting start date on Calendar extender.

How can I restrict the calendar so the user can not select a past date or dates prior to a specific date? And similarly for future date. Or do I need to validate it on

OnClientDateSelectionChanged

Thanks.

Yes, you would need to do some validation. One method you can use though is toremove the arrows that let the user cycle through the months based on a certain month/year combination.

Retaining GridView cell color on postback

I have a GridView in an UpdatePanel in which I use JavaScript to allow the user to change cell colors on the fly. It works great, until a postback occurs in which case, all of the user changes are lost. How do I maintain the cell colors after postback? I am trying to use a Save button to store the status of each cell to a database. Unfortunately, the cell colors are reset immediately, so even the save routine does not work correctly.

Thanks for any help you can provide,

Todd

Here is the script used to change the color of a cell when the user right-clicks on it:

<script type="text/javascript"><!-- /* script for changing the background color of the table cells based on the "Selection Mode" */ document.getElementById('ctl00_MainContentPlaceHolder_gvWafer').onmousemove = MouseMove; document.getElementById('ctl00_MainContentPlaceHolder_gvWafer').onmousedown = MouseMove; document.getElementById('ctl00_MainContentPlaceHolder_gvWafer').oncontextmenu = DontShowContext; document.getElementById('ctl00_MainContentPlaceHolder_gvWafer').onmouseup = MouseUp; // handle the MouseMove event for the GridView control function MouseMove(event) { // IE doesn't pass the event object, so we have to pass it manually if (event == null) event = window.event; /* only select table cells if the right mouse button is pressed and the underlying item is a 'TD' element (table data) */ if (event.button == 2 && event.srcElement.tagName == 'TD') { var cell=event.srcElement; var cellValue=cell.innerHTML; /* display the row and column indexes in the browser status bar */ window.status="row, column = " + cell.cellIndex + "," + cell.parentElement.rowIndex; /* determine which item in the Selection Mode drop down list box is selected */ switch(document.getElementById( 'ctl00_MainContentPlaceHolder_ddlSelectMode').getAttribute( 'selectedIndex')) { case 1: // available /* Don't allow cells marked as QC Samples to be marked Available */ if (cell.style.backgroundColor != '#996600') { // GREEN cell.style.backgroundColor='#00FF00'; } break; case 2: // picked /* Don't allow cells marked as QC Samples to be marked as Picked */ if (cell.style.backgroundColor != '#996600') { if (cellValue >= 20 || cellValue <= 200) { // GRAY cell.style.backgroundColor='#999999'; } else { // WHITE cell.style.backgroundColor='#FFFFFF'; } } break; case 3: // reserved /* Don't allow cells marked as either Picked or QC Samples to be marked as Reserved */ if (cell.style.backgroundColor != '#996600' && cell.style.backgroundColor != '#999999') { if (cellValue >= 20 || cellValue <= 200) { // PURPLE cell.style.backgroundColor='#9933CC'; } else { // WHITE cell.style.backgroundColor='#FFFFFF'; } } break; default: return; } } } /* clear the status bar data */ function MouseUp(event) { window.status = ""; } /* handle the ContextMenu event for the GridView control - Don't show the default context menu */ function DontShowContext(event) { return false; } if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded(); // --></script>

You are going to need to save these styles and reinitalize them on the callback of the UpdatePanel e.g.:

var prm = Sys.WebForms.PageRequestManager.getInstance();

prm.add_endRequest(EndRequestMethod);

prm.add_beginRequest(BeginRequestMethod);

...or you can add your logic to the server side. The problem is that you are rebinding the whole GridView and obviously client-side changes aren't persisted.

-Damien


Get the current PageRequestManager instane and

try to use beginRequest and endRequest


Thanks for both of your inputs. I don't know why I expected the JavaScript to make the changes to the GridView control. I forgot that the GridView control is rendered as a Table and that the JavaScript was simply modifying the Table. I actually took a little bit different route to solve the problem (I didn't see your replies until just a few minutes ago...had email notification turned off by mistake).

So, since the GridView is rendered as a Table and JavaScript cannot change GridView properties, I had to somehow track the changes that were made to the Table and propagate them to the GridView control.

I decided to create a TextBox control in which the JavaScript code would write the changes made to the cells (in the format "[row],[column]=[color]\n"). My VB code then parses out those changes and makes the corresponding change in the GridView control. I make the width and height of the TextBox zero so that it is not visible.

It may not be the best way to accomplish the task, but it is working. Since this is for an intranet application, and I have a ton more work to do, I am going to stick with it. The next time I run into a problem like this I will keep the other suggested solutions in mind.

Thanks,

Todd

Retaining ViewState in Atlas

On my real estate website I have a Search page and a Results page. The Search page contains three linked Atlas cascading dropdowns (CDDs). The user makes some selections on these and then clicks a <search> button to see the results. This opens the Results page, which displays a list of properties meeting the search criteria. I have this working fine, apart from one thing: when the user goes back to the Search page, the CDDs have been reset to their original values. I was wondering if there was an easy way for the Search page to retain its settings. I have a partial solution, but it's not very good. If I set AutoPostBack to "True" for each CDD, they retain their settings when I click the <back> button on the browser. This is pretty horrible though, as it means the whole page gets posted back - undermining the whole purpose of using Atlas in the first place! I have tried enclosing the CDDs in an UpdatePanel (so that only they get posted back and not the whole page), but they just end up flickering all the time as (I guess) they get stuck in a code loop.

Also, setting AutoPostBack to "True" is only effective when the user clicks the browser's <back> button. I want to offer my own button or link in case they arrived at the Results page from another route. I have tried creating a hyperlink to the Search page, adding a button with a PostBackUrl of "Search.aspx" and adding a Response.Redirect command to a button's on_click event. Even with AutoPostBack set to "True" (which I want to avoid), none of these methods works. The CDDs just get reset every time.

Also, the other server controls I have on the Search page (check boxes, conventional drop-down list boxes, etc.) get reset every time too. I've tried looking into ViewState, but I can't get it to work. It looks like I need a way to save the viewstate on exit and somehow retrieve it when I load the page again. I guess I'm missing something fundamental. Any suggestions? Am I barking up the wrong tree? I imagine this kind of thing must have been done many times before and would appreciate a few hints.Any ideas on this? I'd really appreciate some help on something that must be a fairly common problem - or will be as Atlas takes off. Thanks for your interest.

You could try saving the viewstate to sessionstate or to disk

An example of saving viewstate to disk can be found here :
http://aspalliance.com/911


That seems to be on the right track. I'm now saving the values of my page controls to Session State when I exit the page, and retrieving them when I load it. This works fine for all the controls except the CDDs. Since these are populated by WebMethods, I don't seem to have any opportunity to set their SelectedValue properties. To focus on the problem area, I have tried adding a button to my form with a single line of code reading:ddlRegion.SelectedValue = RegionIDWhere RegionID is a value retrieved from the session.This causes an argument out of range exception as follows:[ArgumentOutOfRangeException: 'ddlRegion' has a SelectedValue which is invalid because it does not exist in the list of items.Parameter name: value]I get the same error if I change the variable RegionID to the literal "1" (which is definitely in the list).What it boils down to is this:How can I programatically set the SelectedValue of an Atlas Cascading Dropdown?I know how to save the value to, and retrieve it from, session state, but I don't know how to assign it to an Atlas cascading dropdown list. Any ideas?

1. Perest the CCD by setting the selected value of the cascading extender control ( and not the drop-down) , as explained in the article ( link )

2. and you can retrieve the viewsate ... as explained on this link.http://gandhirohan.blogspot.com/2007/09/cascadingdropdown-control.html

retrieve info dynamically created textbox in update panel

I have a textbox that is created in code in an Ajax Update Panel when then the user clicks on a dropdownlist.

I would then like to retreive the text that user types in:

Dim strTitleAsString =CType(Me.FindControl("txtPrimaryPersonTitle" + intSuggestedPrimaryPersonCount.ToString), TextBox).Text

It gives me an error that it can't find the control.

Can you offer any help??

Have you made sure that the textbox is re-created on postback?

You may also consider creating the textbox statically (in markup) instead of dynamically.
Set Visible=False in the markup, and make it visible in your dropdownlist code.
This prevents most of the problems inherent to dynamic controls.

Jos


hello.

how about a demo page so that we can see what you're doing? it has to be simple enough so that we ca simply copy/paste it in order to test it


Hi,

it can't find the control?

If the contorl still exist, the Id must not write.

I think it is easy to debug to see if the contorl is exist or not, and it is easy to find out what is the correct id of the contorl.

If you still have question,post up a repro of your issue.

Best Regards,

2012年3月24日土曜日

Returning Focus to the top of the page

I have two panels over laying each other. When the user click a button at the bottom of the first panel, that disappears and the panel on top appears, when the event triggers and the Ajax response is processed the page focus remains where the button that was clicked once was and as the information on the second panel is at the top of the page, the user has to scroll up to the top each time. This is obivously something to do with Ajax, but I can't get the page to return to the top. I have tryed using a invisible text box and setting that as having focus when the second panel appears, but this does not work either.

Any suggestions?

I would link internally to the page. So if you're onhttp://www.someurl.com/somepage.aspx after the Ajax, link internally tohttp://www.someurl.com/somepage.aspx# which will jump to the top of the page.

Alternatively you can do a setFocus call to the <body> tag or some other element that is at the top of the page.

Regards,

Tim