Passing value to a user control from asp.net Page - c#

I have following user control my .ascx Page. (Test.ascx)
<uc:Addresses runat="server" itemId='<%# StringId %>'></uc:SNETAddresses>
In the code behind of Test.ascx I have
protected string StringId = "{2A06199B-ED96-42F0-AB9A-602139E58BFB}";
In the code behind of user control Addresses.cs I have:
public string itemId { get; set; }
So basically I want to pass a string to the variable itemId. But Somehow its not getting the value of variable "StringId". This simple thing is taking my so much time. I checked this post asp.net passing string variable to a user control but I am so sorry I could not get the answer. The reply is:
You may need to call DataBind on your Page in CreateChildControls or some other method
I am new to Asp.Net and I didn't get what the user mean here.

You need to call Page.DataBind(), e.g. in your Page_Load() event handler.
Data-binding expressions (<%# ... %>) are only processed when you call the DataBind() method.
Alternatively (instead of using a data-binding expression), you can also simply assign the value to the user control's property from your page's code-behind:
// add an ID to the user control (in the markup)
<uc:Addresses runat="server" id="myControl"></uc:SNETAddresses>
Then in your Page_Load() method simply assign the value to the user control's property:
myControl.itemId = StringId;

Related

Dynamically create a UserControl with parameters

I've created a UserControl that contains a grid.
In main page, users can select options from a combo, then, I need to generate a UserControl for each option that user's selected.
I've 2 problems:
I need to pass the parameters to the user control for configure the grid's datasource, but I don't know how to do it.
If I set default parameters for test, when a PostBack occurs, the user controls are removed.
I don't see any code of yours, so I leave you a simple example here.
First, define a property for the value you need to pass in:
public partial class SomeControl : System.Web.UI.UserControl
{
public int AProperty { get; set; }
...
}
So then, from the aspx where you need to use your user control, first register it as usual:
<%# Register Src="~/MyControls/SomeControl.ascx" TagPrefix="my" TagName="SomeControl" %>
And later use it, and pass the value to the property, like this:
<my:SomeControl runat="server" ID="SomeControl1" AProperty="1" />
You can also set that property from the code behind of your aspx which contains the control, like this:
SomeControl1.AProperty = 1;
Dynamic controls
You can create this controls dynamically like this:
var ctrl = new SomeControl();
ctrl.AProperty = 1;
And later add those controls to a <asp:PlaceHolder in your aspx:
somePlaceHolder.Controls.Add(ctrl);
Upon postback (ie on selectedindexchanged of a dropdownlist), all the controls inside that place holder will desappear, but the information is still in your viewstate, so all you need to do is recreate the corresponding controls inside the same placeholder and the old values from viewstate will be attached to the recreated controls.

Get dynamically generated Controls of current Page

I have a MasterPage website. I'll use the Facebook example to simplify understanding of my purpose.
In default.aspx, i add many DIVs dynamically from code-behind (ie. each div is a SQL result).
In each DIV there's a Label, and also a "Like" HyperLink, listened by a "onclick" JS function that changes "Like" to "Dislike" text in LinkButton and triggers an AJAX call that calls MyMethod(userid, postid) method.
The MyMethod() method changes the Like/Dislike status for the user in SQL.
I want MyMethod() to update the Label too, so MyMethod() would do:
((Label)((Page)HttpContext.Current.Handler).FindControl("lbl_XX")).Text = "foo";
The problem is that i can't get any of the controls of the page.
I also tried a EventHandler added to the LinkButton, but eventually the MyMethod() never gets the Label by FindControl because Page object seems to come without controls.
How can i access the controls of the current page from a method?

How to use a Page variable in User Control?

I have a page with a private variable: AccountData.
This handles all of the account data and I save it in the viewstate between postbacks.
I have a User Control named AccountFavorites that renders all of the account Favorite topics.
When a user decides he wants to cancel one favorite topic he clicks on an asp:LinkButton and it posts back to the server to change the value in the Database.
However, the Control doesn't know what AccountData is, only the page does.
How can I use the AccountData in a postback of the Control?
Can I make the postback go to the page instead?
<myprefix:AccountFavorites runat="server" id="TheAccountFavorites" />
In your page set the info...
protected void Page_Load(object sender, EventArgs e)
{
TheAccountFavorites.TheAccountData=MyAccountData;//assuming you'll load up MyAccountData
}
In your control, expose AccountData as a public property. This will allow you to access it from the page.
public AccountData TheAccountData {get;set;}
This is assuming AccountData was the type name and not something else, like a string. But you can change AccountData to string and it will work.
Since it is page that owns/parents the user control, it is preferable to for the page to know about the specifics of the control, not the other way around. Add AccountData property to the control and in the page's Page_Load do:
uc.AccountData = AccountData;

Asp.net Hidden field not having value in code behind, but *is* retaining value after postbacks

In my ASCX, I have an asp.net hidden field defined as <asp:HiddenField ID="hdnNewAsset" runat="server" />.
In the Code Behind I have the following code:
protected void Page_Load(object sender, EventArgs e)
{
_service = new ArticleDataService(PortalId);
if (!IsPostBack)
{
string rawId = Request[ArticleQueryParams.ArticleId];
DisplayArticleDetails(rawId);
}
if (hdnNewAsset.Value.Trim() != string.Empty)
ProcessNewAsset();
}
Now, in my frontend, I have a javascript function to react to an event and set the hidden field and trigger a postback:
function assetSelected(assetGuid) {
$('input[id*="hdnNewAsset"]').val(assetGuid);
__doPostBack()
}
What's happening is that my hidden field is being set in the markup (chrome shows [
<input type=​"hidden" name=​"dnn$ctr466$Main$ctl00$hdnNewAsset" id=​"dnn_ctr466_Main_ctl00_hdnNewAsset" value=​"98d88e72-088c-40a4-9022-565a53dc33c4">​
] for $('input[id*="hdnNewAsset"]')).
However, when the postback occurs, hdnNewAsset.Value is an empty string.
What's even more puzzling is that at the beginning of Page_Load Request.Params["dnn$ctr466$Main$ctl00$hdnNewAsset"] shows 98d88e72-088c-40a4-9022-565a53dc33c4, and after the postback my hidden field has the same value (so the hidden field is persisting across postbacks), yet I cannot access this value via hdnNewAsset.Value.
Can anyone see what I"m doing wrong?
Ok I figured out the the issue.
The issue is that the code posted above was part of an ASCX user control. That user control was being loaded dynamically into an asp.net placeholder during the Page_Load event of the parent control.
Therefore, it seems that since both of these calls were in Page_Load of their respective calls, the inner control did not have it's values bound in the inner control's page_load. Modifying it so my inner control is loaded in Page_Init instead of Page_Load fixed all bindings.
Not sure if I wrote that in a way that makes sense to the general public.
Edit: It seems this part of the MSDN documentation is relevant to my issue:
If controls are created dynamically at run time or declaratively within templates of data-bound controls, their events are initially not synchronized with those of other controls on the page. For example, for a control that is added at run time, the Init and Load events might occur much later in the page life cycle than the same events for controls created declaratively. Therefore, from the time that they are instantiated, dynamically added controls and controls in templates raise their events one after the other until they have caught up to the event during which it was added to the Controls collection.

ASP.NET: generate property value when adding control to page

Context: ASP.NET 3.5 / C#
Hi,
I created a user control
public partial class MyControl : UserControl
{
// EDIT: example first used "UniqueId" as property name, which was wrong.
public Guid MyId { get; set; }
// ...
}
and this example usage
<uc1:MyControl
ID="myControl"
MyId="443CBF34-F75F-11DD-BE2F-68C555D89123"
runat="server" />
Steps:
Add this control to a web form (aspx)
Expected result:
the HTML for the user control is added, a unique value (corresponding to Guid.NewGuid()) for MyId is set in the ASPX HTML at design-time as the MyId attribute value.
Actual result:
the HTML for the user control is added, a unique value for MyId is not set in the HTML at design time for the MyId Attribute value.
If this is not possible:
Workaround 1: Would it be possible to achieve this using a server control? How?
Workaround 2: is it possible to achieve this using a UserControl design-mode task?
Clarification:
persisting the property value is not an issue, since it never changes for a control intance and is automatically set by ASP.NET through the control declaration in the aspx page.
the MyId attribute does not need to be rendered at runtime.
Gr B!
Custom Design-time Control Features in Visual Studio .NET
You have a couple problems here, but first I will answer your questions about the workarounds.
No you are already using a server control.
No design-mode is to just make the lives of the developer easy, it doesn't effect anything else
You have two problems here. There is already a property called UniqueID I don't know if you were trying to overload that, but the question wasn't clear. The second problem is that your UniqueID essentially not getting stored anywhere. Try the following code:
public Guid UniqueId {
get { return (Guid)ViewState["MyUserControlUniqueId"]; }
set { ViewState["MyUserControlUniqueId"] = value; }
}
That will store the GUID in the ViewState so that you can retrieve it on post backs.
Update: Given your comment you need to override/use this method to add attributes to the rendered content.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.webcontrol.addattributestorender.aspx
If I understand your question correctly, you are exposing a property on your user control called MyId. This allows you to set the property wherever you put that control.
What you also want, is for the rendered HTML to also include this attribute and value.
If that's the case, the property MyId is not passed through to the HTML, it's only because the user control has MyId as a property that it's visible in the designer.
In your user control you will have defined the markup that gets rendered.
So for example if you have:
<asp:Panel runat="Server" Id="myControlDiv">Some other content</asp:Panel>
You can then in your controls prerender event (or wherever else you choose) put
myControlDiv.Attributes.Add("MyId", SomeGuid.ToString())
Which will then get output in the HTML as
<div id="generatedID" MyID="443CBF34-F75F-11DD-BE2F-68C555D89123">Some other content</div>
So you just want a unique ID generated that you only ever use in design time?
Why not override Object.GetHasCode();
And then exposure this as a property?

Categories

Resources