Showing posts with label user. Show all posts
Showing posts with label user. Show all posts

Wednesday, March 28, 2012

PageMethod called within User Control (ascx)

Hi all,

I am trying to call a PageMethod on an AutoComplete extender within an ascx (user control). I am able to do so when the extender sits directly on an ASPX (web form) but would like to reuse the component.

I know to decorate the method with [WebMethod] and [ScriptMethod] attributes and also to make the method static. I know, too, that the parameter names must match the expected signature.

Is it possible to place Page Methods within User Controls or do they have to sit on ASPX pages?

Thanks in advance,

MIKE

I have seen a couple of blog posts saying no and I was trying to do something similar last night and couldn't make it work. I would really perfer the AutoComplete extender and the NumericUpDown extender to have the option to fire events or at least non static methods but I don't think that will be possible under the current Ajax setup.

PageMethod Static Ajax WebService and User Controls

I have a page HostPage.aspx, which is a generic hostpage that will dynamically load Web User Controls at runtime, according to the needs of various other users. Those other Web User Controls will be created by the other users, such that they can put anything they like in that Web User Control, and it will be dynamically populated and put in the HostPage.aspx. They will always use HostPage.aspx, they cannot edit it. This is working as-is, and everything is great.

Now, some users want to put AJAX functionality in their User Controls, such that the HostPage.aspx will contain their User Control, the User Control will contain an UpdatePanel, a ScriptManager, etc.

To enable page methods, we have to set the EnablePageMethods="true" on the scriptmanager, and have to declare a static method *somewhere*. The requirements are such that we cannot be declaring these static methods in the HostPage.aspx, because it cannot know what the controls, and therefore static methods, are until runtime. On the other hand, if we declare these static methods in the User Control, it's not defined in the HostPage, and AJAX PageMethod callbacks fail ("Method myMethod is not defined"), because the page doesn't know of it's existence.

1. Has anyone tried to do something similar to this, namely having AJAX controls in a User Control, which is hosted in a page, yet also needs to use the Page Methods, yet cannot declare them in the page (I know, that's pretty specific).

2. Any ideas on how this might be accomplished?

I'm thinking of using Reflection or DynamicMethod (http://msdn2.microsoft.com/en-us/library/system.reflection.emit.dynamicmethod.aspx) to make this happen, such that at runtime, the page will examine its child controls for any static methods with the ScriptService attribute, and then dynamically create a static method on itself with the same name, calling the child, but that is rather involved and I fear the performance risk of this (if this whole idea is even possible). Plus, the generated method wouldn't exist until after the controls exist, and I'm not sure where that falls in relation to the timing of the AJAX extensions (looking for the MethodName). It might be (probable) that the handler is looking for the method even before the controls are initialized, in which case that idea won't fly.

You can't do that... as described here (http://www.singingeels.com/Articles/Using_Page_Methods_in_ASPNET_AJAX.aspx) Page Methods are only on pages :)

But you can get what you want if you make your user control register a "web service" as in this article:http://www.singingeels.com/Articles/Consuming_Web_Services_With_ASPNET_AJAX.aspx

If your users aren't able to add webserivces (I really don't know the situation your building)... then they can register a regular old "AsyncPostBack" and wire it up themselves (sorry, no article on that yet).


Right, I understand completely the concept of PageMethods, that they are on pages, etc. That's why this is a bit of a tricky spot.

I guess what I'm looking for is whether anyone has come up with anything clever to get around this situation (PageMethods from a Usercontrol). The usersare free to create and consume their own webservices, if they like, but if possible, I would like to give them this functionality for this situation.


OK, I believe it's Page.ClientScript.RegisterAsyncPostBack or maybe ScriptManager.RegisterAsycnPostBack ( I can't remember )... either way, it'll post back to the page... and ultimately the user control, and fire an event (on the user control).

That'll work just like the page methods... (a little better actually for what you're doing)

PageMethods call from user controls (ascx)

Hello,

i am looking for a way to call webmethods defined in an (ascx) user control (not a web form page aspx) using PageMethods.{MethodName}. For now, i only get a javascript error saying that PageMethods is not defined. Is there a different syntax to acces thos methods or is it just not possible ?

Thank you for your help

thomas

Any answer would be appreciated.

Thank you

thomas


hello.

currently, you can only call web service methods or page methods (and in this case, the methods must be static)

Monday, March 26, 2012

PageRequestManagerParseErrorException

Hello. I'm have the problem with UpdatePanel. When the user does click on de button I call a method

Button1_Click

This method call other page in modo modal where the user type a password. If this password is ok I'll try to use

UpdatePanell2.Update() but I can′t call the page2 in modo modal because appear this error.

Read this to avoid this issue:

http://weblogs.asp.net/leftslipper/archive/2007/02/26/sys-webforms-pagerequestmanagerparsererrorexception-what-it-is-and-how-to-avoid-it.aspx

PageRequestManagerParserError in IE6 and 7

Hi,

I've created a pretty simple custom control that filters items based on categories the user selects in a drop down box.
Here's the error I'mintermittently getting in IE6 and IE7 but not any mozilla-based browsers.

error

Because of it's intermittent nature it seems like something out of my control...
I've made sure there are no Response.Write(), Response Filters, HttpModules running and that server trace isn't enabled.

I've used Fiddler to look at the responses but can't find the offending part in the error message.

I've googled the error and found this:

http://forums.asp.net/p/1037846/1437627.aspx

I am using a VirtualPathProvider to map requests to items in a cms, but the article above deals with an incorrect formaction being returned in the httpmessage. I've checked the formaction being returned and it is correct.

I'm at a loss. This is a real pain because a lot of time has been invested in using Asp.Net Ajax for our new site and this may make us have to rethink that decision.

Here is the code for my custom control.

using System;

using System.Data;

using System.Configuration;

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;

using System.Collections;

using System.Collections.Generic;

using System.Text;

namespace Unwrong.Controls

{

publicclassFilterList :Control,INamingContainer

{

privatestring _Category;

privateList<FilterListItem> _Items =newList<FilterListItem>();

privateint _MaxVisibleItems;

privateint _Position = 0;

privatestring _CssClass;publicstring Category

{

get {return _Category; }

set { _Category =value; }

}

publicList<FilterListItem> Items

{

get {return _Items; }set { _Items =value; }

}

publicList<FilterListItem> ItemsInCategory

{

get {return GetItemsInCategory(); }

}

publicint MaxVisibleItems

{

get {return _MaxVisibleItems; }

set { _MaxVisibleItems =value; }

}

publicint Position

{

get {return _Position; }set { _Position =value; }

}

publicstring CssClass

{

get {return _CssClass; }

set { _CssClass =value; }

}

protectedoverridevoid OnInit(EventArgs e)

{

Page.RegisterRequiresControlState(this);base.OnInit(e);

}

protectedoverridevoid AddParsedSubObject(Object obj)

{

if (objis Unwrong.Controls.FilterListItem)

{

Items.Add((Unwrong.Controls.FilterListItem)obj);

}

}

protectedoverridevoid CreateChildControls()

{

System.Collections.IEnumerator myEnumerator = Items.GetEnumerator();

while (myEnumerator.MoveNext())

this.Controls.Add((FilterListItem)myEnumerator.Current);

}

protectedoverrideobject SaveControlState()

{

FilterListViewstate state =newFilterListViewstate();

state.Category = Category;

state.Position = Position;

return state;

}

protectedoverridevoid LoadControlState(object state)

{

if (state !=null)

{

Category = ((FilterListViewstate)state).Category;Position = ((FilterListViewstate)state).Position;

}

}

protectedoverridevoid Render(HtmlTextWriter w)

{

List<FilterListItem> itemsToDisplay = GetDisplayItems();w.Write(@dotnet.itags.org."<script language='javascript' type='text/javascript'>

<!--

function hide(id){

try{

var obj=$get(id);

obj.style.visibility='hidden';

}catch(e){}

}

function show(id){

try{

var obj=$get(id);

obj.style.visibility='visible';

}catch(e){}

}

//-->

</script>

");w.Write("<div class=\"column1\">");

w.Write(GetItemsInColumn(0));

w.Write("</div>");

w.Write("<div class=\"column2\">");

w.Write(GetItemsInColumn(2));

w.Write("</div>");w.Write("<div class=\"column3\">");

w.Write(GetItemsInColumn(4));

w.Write("</div>");

}

privatestring GetItemsInColumn(int index)

{

List<FilterListItem> items = GetDisplayItems();

// Check if any items are at the necessary indeces.

if (items.Count > index)

{

StringBuilder sbHtml =newStringBuilder();

// Create the html for two projects.

for (int i = 0; i < 2; i++)

{

index += i;

if (items.Count > index)

{

FilterListItem item = items[index];

sbHtml.Append("<div class=\"project\" ");

sbHtml.Append("onmouseover=\"this.style.backgroundColor='#E1E1E1'; hide('" + ClientID +"_title" + index +"'); show('" + ClientID +"_details" + index +"');\" ");

sbHtml.Append("onmouseout=\"this.style.backgroundColor='#FAFAFA'; show('" + ClientID +"_title" + index +"'); hide('" + ClientID +"_details" + index +"');\" ");

sbHtml.Append(">");if (!String.IsNullOrEmpty(item.ProjectLink))

{

sbHtml.Append("<a href=\"" + item.ProjectLink +"\"><img src=\"" + item.Image +"\" alt=\"" + item.Title +"\" title=\"" + item.Title +"\" /></a>");

}

elseif (!String.IsNullOrEmpty(item.LiveLink))

{

sbHtml.Append("<a href=\"" + item.LiveLink +"\" target=\"_blank\"><img src=\"" + item.Image +"\" alt=\"" + item.Title +"\" title=\"" + item.Title +"\" /></a>");

}

else

{

sbHtml.Append("<img src=\"" + item.Image +"\" alt=\"" + item.Title +"\" title=\"" + item.Title +"\" />");

}

sbHtml.Append("<div id=\"" + ClientID +"_title" + index +"\" class=\"title\">");

sbHtml.Append(item.Title);

sbHtml.Append("</div>");

sbHtml.Append("<div id=\"" + ClientID +"_details" + index +"\" class=\"details\">");

if (!String.IsNullOrEmpty(item.ProjectLink))

{

sbHtml.Append("<a href=\"" + item.ProjectLink +"\">View Details</a>");

}

else

{

sbHtml.Append("<span class=\"strikethrough\">View Details</span>");

}

if (!String.IsNullOrEmpty(item.LiveLink))

{

sbHtml.Append("<br/><a href=\"" + item.LiveLink +"\" target=\"_blank\">View Live</a>");

}

else

{

sbHtml.Append("<br/><span class=\"strikethrough\">View Live</span>");

}

sbHtml.Append("</div>");sbHtml.Append("</div>");

}

}

return sbHtml.ToString();

}

else

{

returnstring.Empty;

}

}

privateList<FilterListItem> GetItemsInCategory()

{

List<FilterListItem> itemsInCategory =newList<FilterListItem>();

// Remove all items that aren't in current category.

foreach (FilterListItem itemin Items)

{

if (IsItemInCategory(item))

{

itemsInCategory.Add(item);

}

}

return itemsInCategory;

}

privateList<FilterListItem> GetDisplayItems()

{

List<FilterListItem> itemsInCategory = GetItemsInCategory();

List<FilterListItem> itemsToDisplay =newList<FilterListItem>();

int count = MaxVisibleItems;if (Position + MaxVisibleItems > itemsInCategory.Count)

{

count = itemsInCategory.Count - Position;

}

return itemsInCategory.GetRange(Position, count);

}

privatebool IsItemInCategory(FilterListItem item)

{

if (String.IsNullOrEmpty(Category) || Category.ToLower() =="all")

{

returntrue;

}

foreach (string cin item.Categories)

{

if (c.ToLower().Trim() == Category.ToLower().Trim())

{

returntrue;

}

}

returnfalse;

}

}

[Serializable]

publicclassFilterListViewstate

{

publicstring Category;publicint Position;

}

}

Here is the code for page where it is used:

<asp:UpdatePanelID="UpdatePanel1"runat="server"UpdateMode="Conditional">

<ContentTemplate>

<tableid="filter-widget-bar"cellpadding="0"cellspacing="0"border="0">

<tr>

<tdclass="col1">

<imgsrc="/assets_new/images/projects.gif"alt="Projects"/>

</td>

<tdclass="col2">

<tableid="filter-widget"cellpadding="0"cellspacing="0"border="0">

<tr>

<td>

<ctrl:ImageButtonID="btnPreviousProject"runat="server"CssClass="previous"ImageUrl="~/assets_new/images/btn_previous.gif"OnClick="btnPreviousProject_Click"BorderWidth="0"AlternateText="Previous"/>

</td>

<td>

<asp:DropDownList

ID="lstFilter"

OnSelectedIndexChanged="lstFilter_OnSelectedIndexChanged"

AutoPostBack="true"

runat="server">

<asp:ListItem>Favourites</asp:ListItem>

<asp:ListItem>All</asp:ListItem>

<asp:ListItem>Games</asp:ListItem>

<asp:ListItem>Websites</asp:ListItem>

<asp:ListItem>Applications</asp:ListItem>

<asp:ListItem>Playthings</asp:ListItem>

<asp:ListItem>Cms</asp:ListItem>

<asp:ListItem>Flash</asp:ListItem>

<asp:ListItem>Html</asp:ListItem>

</asp:DropDownList>

</td>

<td>

<ctrl:ImageButtonID="btnNextProject"runat="server"CssClass="next"ImageUrl="~/assets_new/images/btn_next.gif"OnClick="btnNextProject_Click"BorderWidth="0"AlternateText="Next"/>

</td>

</tr>

</table>

</td>

<tdclass="col3">

</td>

</tr>

</table>

<divid="projects">

<ctrl:FilterListID="lstProjects"runat="server"MaxVisibleItems="6">

<ctrl:FilterListItemrunat="server"Image="repository/uploads/projects/ilovedust.jpg"Title="ILoveDust"ProjectLink="http://www.unwrong.com/projects/ilovedust/"LiveLink="http://www.ilovedust.com">

<ctrl:Categoriesrunat="server">

<ctrl:Categoryrunat="server">Flash</ctrl:Category>

<ctrl:Categoryrunat="server">Cms</ctrl:Category>

<ctrl:Categoryrunat="server">Favourites</ctrl:Category>

<ctrl:Categoryrunat="server">Websites</ctrl:Category>

</ctrl:Categories>

</ctrl:FilterListItem>

<ctrl:FilterListItemrunat="server"Image="repository/uploads/projects/tado.jpg"Title="Tado"ProjectLink="http://www.unwrong.com/projects/tado/"LiveLink="http://www.tado.co.uk">

<ctrl:Categoriesrunat="server">

<ctrl:Categoryrunat="server">Flash</ctrl:Category>

<ctrl:Categoryrunat="server">Favourites</ctrl:Category>

<ctrl:Categoryrunat="server">Websites</ctrl:Category>

</ctrl:Categories>

</ctrl:FilterListItem>

<ctrl:FilterListItemrunat="server"Image="repository/uploads/projects/communicatorworld.jpg"Title="Communicator World"ProjectLink="http://www.unwrong.com/projects/communicator/"LiveLink="http://www.communicatorworld.co.uk">

<ctrl:Categoriesrunat="server">

<ctrl:Categoryrunat="server">Flash</ctrl:Category>

<ctrl:Categoryrunat="server">Cms</ctrl:Category>

<ctrl:Categoryrunat="server">Favourites</ctrl:Category>

<ctrl:Categoryrunat="server">Websites</ctrl:Category>

</ctrl:Categories>

</ctrl:FilterListItem>

</ctrl:FilterList>

</div>

</ContentTemplate>

</asp:UpdatePanel>


Hi,smeeg

This happens when the machineKey used to encrypt/decrypt the viewstate was changed, and more likely this will happen if you keep the page idle for a long time. To avoid this, you need to have a static machineKey.

Check this articlehttp://blog.g9th.com/2007/01/14/unable-to-validate-data-at-systemwebconfigurationmachinekeysectiongetdecodeddata.aspx

Let me know if you need more info.
You can also see this thread for more help:http://forums.asp.net/t/1115331.aspx

Thanks

NOTE:This response contains a reference to a third party World Wide Web site. Microsoft is providing this information as a convenience to you. Microsoft does not control these sites and has not tested any software or information found on these sites; therefore, Microsoft cannot make any representations regarding the quality, safety, or suitability of any software or information found there. There are inherent dangers in the use of any software found on the Internet, and Microsoft cautions you to make sure that you completely understand the risk before retrieving any software from the Internet.

Wednesday, March 21, 2012

Partial page rendering of user control

I have a user control. This user control has an update panel in it. Everything works great with the user control.

Now when I include the user control into a .aspx page I have it set up so that after a specific delay in seconds (set by a timer) it loads. But when it loads it causes a complete page refresh. I would like it so that only the area where the control is placed is refreshed.

I thought about wrapping the user control in the .aspx with an update panel but it throws a message of couldn't find a control in the user control. Basically it is a update panel inside of an update panel each mode set as conditional. When I run the user control without the update panel everything works fine.

Anyone have an idea of to go about this. Here is a bit of code:

<

asp:TimerID="timerCalendar"runat="server"OnTick="loadCalendar"Interval="2000"enabled="false"></asp:Timer>
<asp:UpdatePanelid="upCalendar"runat="server"UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTriggerControlID="timerCalendar"eventname="Tick"/>
</Triggers>
<ContentTemplate>
<asp:PlaceHolderID="phCalendar"runat="server"></asp:PlaceHolder>
</ContentTemplate>
</asp:UpdatePanel>User control is dynamically loaded and put into the placeholder when the timer is enabled.

thanks ^_^

Have you tried removing the UpdatePanel from the usercontrol... and instead of using a "PlaceHolder" to dynamically add your UserControl to... use an "UpdatePanel" in your page... then instead of "myPlaceHolder.Controls.Add(myUC);" do "myUpdatePanel.Controls.Add(myUC);"?


Good idea. Didn't think of that.

Question though. Within the user control I have a gridview. Would I add a trigger dynamically to the update panel in the page where the user control is dynamically loaded as well and set the trigger id to gridview in the control (do a findcontrol on the control id) or how would I go about getting the gridview to use the update panel as well?

Hope that makes sense. :)


Discovered the solution. I didn't have the mode for each updatepanel to conditional. Once I did this everything worked just fine. :)

partial page update in a usercontrol on a master page

OK, I've installed AJAX Extensions, watched the tutorial video and tried to use the partial page update as follows: I have a user control which contains hyperlinks for paging back and forth and a datalist which displays the current page of products: <asp:UpdatePanelID="UpdatePanel1"runat="server"> <ContentTemplate> <asp:HyperLinkID="hLink_Previous"CssClass="paging_Text"Visible="false"runat="server">Previous</asp:HyperLink> <asp:LabelID="label_Paging"CssClass="paging_Text"Visible="false"runat="server"/> <asp:HyperLinkID="hLink_Next"CssClass="paging_Text"Visible="false"runat="server">Next</asp:HyperLink> <asp:DataListID="dataList_Products"RepeatColumns="2"RepeatDirection="Horizontal"runat="server"EnableViewState="False"OnItemCommand="dataList_Products_ItemCommand"> <ItemTemplate> <tableclass="dataList_Products_Table"cellpadding="0"align="left"> <trclass="dataList_Products_Table_Row"> <tdalign=centerclass="dataList_Products_Table_Cell_1"> <ahref='Product.aspx?P=<%# Eval("ProductID")%>'> <imgclass="small_Image"src='ProductImages/<%# Eval("Image1FileName")%>'/> </a> </td> <tdclass="dataList_Products_Table_Cell_2"> <aclass="product_Name"href='Product.aspx?P=<%# Eval("ProductID")%>'> <%# Eval("Name")%> </a> <br/> <spanclass="product_Description"> <%# Eval("Description")%> <br/> <br/> Price: </span> <spanclass="product_Price"> <%# Eval("Price","{0:C}")%> </span> <br/> <asp:ButtonID="btn_AddToCart"Text="Add to Cart"CssClass="small_Button_Text"CommandArgument='<%# Eval("ProductID")%>'runat="server"/> </td> </tr> </table> </ItemTemplate> </asp:DataList> </ContentTemplate></asp:UpdatePanel> I use this within the contentPlaceHolder on the Master page. I want only this bit to update when I navigate between pages but looking at the triggers collection, I can only see the datalist and ScriptManager controls - how do I hook into the previous and next page hyperlinks and their onClick event to enable the page update ? Thanks AR

Hi,

HyperLink control doesn't have click event.

You can use LinkButton control that has a similar layout like hyperlink to achieve so.

Hope this helps.