Wednesday, March 28, 2012

How do I Select Values in Cascading Dropdowns

Using VS 2005, ASP.NET AJAX 1.0 and AJAX Toolkit 10618

I have 2 dropdowns using the Cascading Dropdown from the toolkit, these are both connected to a web service and this all seems to work fine. No other Ajax type controls are being used on the page.

How do I set the dropdown values from server side code? or any method to change the selected item in each dropdown once they have been set.

I did manage to get the selected value to pass in with the data from the callbacks on the web service and this works fine when the page first opens, but any attempt to change the selected values once the page is open either through the web service or server code does not work; both drop downs keep their previous setting. I have setup a breakpoint on the data (in the web service) before it is sent back to the page and I can see the item that should be selected but yet the dropdowns do not change their selected value.

I have tried combobox.selectedvalue = "Some Value" and the GetTargetProperties method doesn't seem available anymore.

I have this nagging suspicious feeling I am missing something obvious.

Please Help

This video has a walk though.

http://asp.net/learn/videos/view.aspx?tabid=63&id=77


I had used the information in this video to get started which was a great help.

Now I need to now how to set a selected value in the dropdowns. I can get the values set on the initial page load, it is changing the values once the page is loaded and the initail values have been set. The setting of the selected values are done through code. It seems that the dropdowns have a memory once their intial selected values are set and cannot be changed.


figured it out!

Had a look at the toolkit source code and it was obvious...

cascadingdropdown1.clientstate = "String of selected value"

All is good in the world again!


Turns out SelectedValue works as well. I was trying to do this on the dropdown itself instead of the cascading control.

How do I scroll to the top of a page to view a ValidationSummary if there is a validation

Hi All,

So, I'm starting a new post that is related to my initial post from approximately 7 months ago (http://forums.asp.net/t/1040392.aspx). My hope is to finally find a solution to this problem... here is the issue:

A couple of our Ajax enabled pages have a lot of form fields, thus a user has to scroll to the bottom of the page to view the Submit button. When a control's RequireFieldValidator's EnableClientScript property is set to"true", upon a validation error the page will scroll up to the ValidationSummary. This is the functionality that I desire. But, when a control's RequireFieldValidator's EnableClientScript property is set to"false", upon a validation error the page does NOT scroll up to the ValidationSummary. Why not?

Here is a quick code sample to illustrate the problem:

<%@dotnet.itags.org.PageLanguage="C#"AutoEventWireup="true"CodeFile="ValidationTest.aspx.cs"Inherits="Register_Playground_Shamus_ValidationTest" %>
<!DOCTYPEhtmlPUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<htmlxmlns="http://www.w3.org/1999/xhtml">
<headrunat="server">
<title>Validation Test</title>
</head>
<body>
<formid="form1"runat="server">
<div>
<asp:ScriptManagerID="asmScriptManager"EnablePartialRendering="true"runat="server"/>
<asp:UpdatePanelID="udpUpdatePanel"runat="server">
<ContentTemplate>
<asp:ValidationSummaryID="valSummary"runat="server"/>
<!-- Lots of space to induce scrolling upon a validation error. -->
<p>Scroll Down</p>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<asp:TextBoxID="TextBox1"runat="server"/><asp:RequiredFieldValidatorID="RequiredFieldValidator1"EnableClientScript="true"ControlToValidate="TextBox1"runat="server"ErrorMessage="* TextBox1"/><br/>
<asp:TextBoxID="TextBox2"runat="server"/><asp:RequiredFieldValidatorID="RequiredFieldValidator2"EnableClientScript="false"ControlToValidate="TextBox2"runat="server"ErrorMessage="* TextBox2"/><br/>
<asp:ButtonID="Button1"runat="server"Text="Button"/>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>

And, the codebehind... 
using System;using System.Data;using System.Configuration;using System.Collections;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;public partialclass Register_Playground_Shamus_ValidationTest : System.Web.UI.Page{protected void Page_Load(object sender, EventArgs e) { }}

The only difference between TextBox1 and TextBox2 is their RequiredFieldValidator's EnableClientScript property (TextBox1 is true and TextBox2 is false). To reproduce the issue:

    Load the page, scroll to the bottom and click the "Button" without entering any text into the text boxes.The page will scroll to the top and you will see the validation summary (good!).Scroll back down to the bottom of the page and put some text into the first textbox. Click the "Button".The page will NOT scroll to the top (bad!).

All I want is for the page to scroll to the top in both scenarios.

Thanks,
-Shamus

So, I fixed the problem with a hack... here is the new codebehind code:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partialclass Register_Playground_Shamus_ValidationTest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
Page.Validate();
if (!Page.IsValid)
{
ScriptManager.RegisterStartupScript(this,this.GetType(),"ReturnToTop","setTimeout(\"window.scrollTo(0,0)\",1);",true);
}
}
}
}

By adding a 1 millisecond timeout before calling window.scrollTo() it now works. If you remove the timeout, then when there is a validation error on Textbox2 the page will not scroll to the top. Personally, I hate hacks like this... I would still love to understand why the client vs. server-side validators behave so differently.

I hope this hack helps somebody else...

-Shamus


Yes sure, it will help for othersSmile

How Do I Reset Scroll Position Inside UpdatePanel?

Hello,

I have a UserControl inside an UpdatePanel. The UserControl contains several DIVs that I show and hide through partial postback. I want the contents of each DIV to be scrolled to the top when I show it. I have tried using the ScriptManager to set focus onto the topmost control of each DIV when I show it, but it doesn't work. I have also tried through javascript to no avail. I know this is kind of the opposite of the behavior that many folks want from AJAX, but I need it for this piece of my application. I have tried searching but all examples are page-centric, not usercontrol-centric and speak to SmartNavigation.

Any help is appreciated.

Brendan

not sure if this would help, but I found something interestingin terms of firing off some js code during a partial page update :

http://ajax.asp.net/docs/ClientReference/Sys.WebForms/PageRequestManagerClass/default.aspx

It was particularly useful for displaying a message to the user to indicate something was happening...

Good luck,

Bob


I ended up just using this in the codebehind of the ascx:

ScriptManager.RegisterStartupScript(Page,typeof(PageTemplate),"Focus","focus();",true);

And including this function in a .js file (one line for each section):

function focus() {
try { window.location.href='#IA'; } catch (err) {}
try { window.location.href='#IB'; } catch (err) {}
try { window.location.href='#IC'; } catch (err) {}
try { window.location.href='#ID'; } catch (err) {}
try { window.location.href='#IIA'; } catch (err) {}
try { window.location.href='#IIB'; } catch (err) {}
try { window.location.href='#IIC'; } catch (err) {}
}

Seems to work on all but the initial page change, which is 'good enough' for me at this stage.

How do I reset a ModalPopup?

How do a reset the contents of a ModalPopup that has been closed (using the .Hide() method or by clicking the cancel button) to it's initial state (at page load)?

I am using a ModalPopup control that contains a UserControl that allows users to search for records in a database. If they find a match, they can click the 'Select' link in the GridView (where the subsequent event handler calls the ModalPopup.Hide() method). They can also click on the Cancel button to close the popup if they don't find what they are looking for.

Everything is working perfectly, except after the ModalPopup has been used once, subsequent use shows the ModalPopup in the exact state it was when it was closed, either by the .Hide() method or the cancel button.

Is there a way around this?

If its a usercontrol in the modalpopup why not create a public reset method in the usercontrol to set all the values back to "" or whatever needs to be done. You could call that right before your .hide(). It sounds like the viewstate of the controls are on. You may be able to kill viewstate on your usercontrol or set initial values, but that could potentially cause problems depending if your user control posts back a bunch of times.

HTH,

AjaxButter


I have started down the road of creating a .ResetForm() method for the user control and will see if that works.

I am hopeful that your suggestion about disabling the ViewState will work, since ideally the ModalPopup should be at it's initial state whenever it's loaded and this would involve the least amount of effort (and code to test). The only issue here might be the use of UpdatePanels for partial-page postbacks (both in the main page on in the popup), so it might not work as hoped.

I guess my best option will be to leave the ModalPopup.TargetID property blank (if it's not required) and handle showing the popup from a button Click() event that resets the UserControl first.

Thanks for the assistance.


Creating a reset event in the UserControl and calling it after certain events works for simple controls (manually created and handled forms). There are still some issues remaining...

Trapping the cancel button click event and performing a reset there causes a full page refresh since it's not wired up through the ModalPopupExtender control (and it can't be part of the UpdatePanel in the popup). Maybe I'm doing something wrong here?

If the ModalPopup contains a UserControl with a FormView (for inserting & updating), the data remains as is after the cancel button is clicked. I tried disabling the ViewState, but since the page has not been refreshed, the FormView stays the same. I also tried creating a _Click() method for the cancel button, but the event doesn't seem to get called for some reason.

Do I have to do some funky client-side scripting to get this to work?


Nevermind... I did some more playing and figured out what I was doing wrong. Staring at it for too long sometimes prevent you from seeing the forest through the trees! Wink

If I moved the cancel button into the UpdatePanel in the popup (and left the ModalPopupExtender.CancelControlID property blank), then this started to work as hoped (without the full page refreshes).

Resetting the FormView inside the UserControl turned out to be as simple as calling for the FormView.ChangeMode() method and setting it to the default mode (insert in this case) and then calling the DataBind() method (may not be needed?).

If anyone else agrees, please mark this post as an answer.

How do I redirect to other pages?

I understand that Altas doesn't yet support request.response

But how do I navigate to other pages??

If you are still wondering about this, you can use RegisterClientScriptBlock to insert a piece of javascript to redirect the page:

ClientScript.RegisterClientScriptBlock(me.gettype,"window","window.location='PageName.aspx'", true)


i had the same problem but i just changed it to an anchor

How do I recognize dynamic buttons as triggers for updating updatepanels?

I have two updatepanels on a page each with a datagrid inside the panels. I need updatepanel B to update it's datagrid when a LinkButton is clicked inside udatepanel A's datagrid. The linkbuttons are dynamically generated for each row of the datagrid.

Thanks

Braden

Stripped Down Example:

<asp:UpdatePanel id="pnl1" runat="server">
<ContentTemplate>
<asp:datagrid id="dgA" runat="server" > ... <asp:LinkButton ID="lbtnSelect" CommandArgument=' ... ' runat="server">...</asp:LinkButton> ... </asp:datagrid>
</ContentTemplate>
</asp:UpdatePanel>

<!-- Next Panel -->

<asp:UpdatePanel id="pnl2" runat="server">
<ContentTemplate>
<asp:datagrid id="dgB" runat="server" > ... </asp:datagrid>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="lbtnSelect" EventName=" ... "/>
</Triggers>
</asp:UpdatePanel>

Unless I misread your post, I think that all you need to do is add the following line inside of your event handler for the link buttons (lbtnSelect_Click, or similar):

pnl2.update();

This should update your pnl1 because the linkbutton's click event fired inside of pnl1, andprogrammatically updating pnl2 with pnl2.update() should take care of updating the other datagrid (dgB). You can get rid of the <Triggers> definition too.

How do I recieve a JavaScript object as a webmethod parameter?

I create a custom JavaScript object on the client side attempted to send to a webmethod and I kinda got it - but do not know how to get the date. The test method looks like this:

[WebMethod]
public string TestMethod(Object obj)
{
return "test";
}

So how can cast this in to the right object to access the data? I can see the contents if I watch it but don't know how to cast it to an object I can use it

Assuming your javascript object is something like the following

{index:-1,fileId:-1,fileExt:\"xls\",issueDate:\"1 Jan 2007\"}

you can create a structure in your serverside code to handle it

Public Structure Doc
Public index As Integer
Public fileId As Long
Public fileExt As String
Public issueDate As Date
End Structure

<WebMethod()> _
Public Function SaveDocs(ByVal docs As Doc()) As Doc()


One more question - if you don't mind:

If my JSON contains an Array - Can you tell how to make that happen? :


My BO:

 [Serializable]public class Supplier : Base {public string Name {get;set; }public string Phone {get;set; }public string Fax {get;set; }public string Website {get;set; }public string Status {get;set; }public Site Site {get;set; }public DateTime Since {get;set; }public Array Contacts {get;set; }public Supplier() {this.Site=new Site();this.Contacts =new Member[0]; } }

Member is also another Object.

My JSON looks something like:

Supplier = {"ID":-1,"Name":"","Phone":"","Website":"","Site":{"Address1":"","Address2":"","City":"","State":{"Name":"","Abbreviation":"","ID":-1},"ZipCode":""},"Contacts":[]};

Its the Contacts that is tripping me up.


Asp.net ajax does the trick for us, I mean the serialization/deserialization.


But for some reason it not filling all the objects - I check the JS object prior to calling the webmethod and the fields are populated but when it casted in the server object - some properties are not filled. Also, my other question is how to pass the array object that is a property of the JS object.


My mistake - I was expecting to receive the parent object and passing the child.