How can I pass user control properties to the page AND make these properties available to all methods on the page (and not just to one method that is fired on a control action, e.g. onControlClick)
I have a set up of essentially 3 pages:
user control (ascx/cs)
class (cs) - that contains user control properties
host page (aspx/cs) - references the user control
The user control consists of 3 interrelated dropdowns. I'm having success passing these dropdown values through a class onto the page via an event that is fired when a user clicks on the dropdown menu. So this way the host page is continously aware of the values in the user control. However, I want the page to use the control's properties (stored in a class) on all of its methods - how do I make this user control class available to all?
Also I'm using ASP.NET and C# by the way.
Here's the Code (not sharing the full code here - just the snippets of a similar code block)
On the ASPX for Menu Host Page:
<linked:LinkMenu2 id="Menu1" runat="server" OnLinkClicked="LinkClicked" />
Host Page (cs):
protected void dropdownclicked(object sender, ddtestEventArgs e)
{
if (e.Url == "Menu2Host.aspx?product=Furniture")
{
lblClick.Text = "This link is not allowed.";
e.Cancel = true;
}
else
{
// Allow the redirect, and don't make any changes to the URL.
}
}
Host Page (aspx)
<asp:dropdowncustom ID="dddone" runat="server" OnddAppClicked="dropdownclicked" />
Control (cs)
public partial class usercontrol_tests_dropdown1 : System.Web.UI.UserControl
{
public event ddtestEventHandler ddAppClicked;
}
public void selectapp_SelectedIndexChanged(object sender, EventArgs e)
{
ddtestEventArgs args = new ddtestEventArgs(selectlink.SelectedValue);
ddAppClicked(this, args);
}
Class:
public class ddtestEventArgs : EventArgs
{
// Link
private string link;
public string Link
{
get { return link; }
set { link = value; }
}
public ddtestEventArgs(string link)
{
Link = link;
}
}
public delegate void ddtestEventHandler(object sender, ddtestEventArgs e);
Hopefully this is what you're after. The best way to do it is to expose your controls as public properties from your user control. So, in your user control, for each drop down list add a property:
public DropDownList DropDown1
{
get { return dropDownList1; }
}
public DropDownList DropDown2
{
get { return dropDownList2; }
}
You can do the same for any other properties you want to access on the host page:
public string DropDown1SelectedValue
{
get { return dropDownList1.SelectedValue; }
set { dropDownList1.SelectedValue = value; }
}
Then, from your host page you can access the properties through the user control:
string value = UserControl1.DropDown1SelectedValue;
or
string value = UserControl1.DropDownList1.SelectedValue;
Here's a couple of other answered questions that you might find useful as I think (if I've understood correctly) this is what you're doing:
Getting data from child controls loaded programmatically
How to change the value of a control in a MasterPage.
Related
using xamarin forms & PCL.
i want to validate the Picker using the Behavior to ensure that user picked an item from the Picker.
my behavior class is
public class PickerValidationBehaviour :Behavior<Picker>
{
private Picker _associatedObject;
public string PropertyName { get; set; }
protected override void OnAttachedTo(Picker bindable)
{
base.OnAttachedTo(bindable);
_associatedObject = bindable;
if (_associatedObject.SelectedIndex < 0 )
{
HandleValidation();
}
}
private void HandleValidation()
{
}
private void _associatedObject_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected override void OnDetachingFrom(Picker bindable)
{
base.OnDetachingFrom(bindable);
_associatedObject = null;
}
}
}
and i was stuck because i want execute the validation before user action, such that the submit button will be hidden until the user fill the form.
and beside if there is any easy efficient way that i can perform the validation please mention it.
I think this scenario you should put logic in VM instead of using behavior.
Cause behavior can change some UI element, like color something and most of them are the element itself's property.
In your case, you want to change another element in Page. There is a problem, how to access another element in your page.
If you binding SelectedIndex in you VM, and when property changed you can raise another property which controls the submit button. That will be easier then do it in behavior.
common class file common.cs: This file, I have added by clicking add->new items-> class
public class common
{
public int v,n;
public int da()
{
return n= v;
}
}
Another file: It's an webpage file name is a1.aspx.cs:
common c = new common();
c.v = Convert.ToInt32(TextBox1.Text);
c.da();
Response.Redirect("ulogin.aspx");
the value from a text box stores in c.v variable
So, now, I want the value which was given in the textbox1.text in another webpage file named as ulogin.aspx.cs
I used this code:
common d=new common();
d.da();
Label1.Text = Convert.ToString(d.n);
but after running it shows the value as 0.....
In a web application, you'll need to persist the information somewhere common (typically Session for per user info or Application for per application info) so that it can be used between different pages & user controls in your application.
I'd suggest adding a Session backed property to your page & usercontrol which accesses a common Session["variable"]. Something like the following.
(i.e. lets imagine your code was being exectued on a button click)
a1.aspx.cs
public int ValueToStore
{
get
{
return Session["ValueToStore"] != null
? (int)Session["ValueToStore"]
: 0
}
set
{
Session["ValueToStore"] = value;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
ValueToStore = Convert.ToInt32(TextBox1.Text);
Response.Redirect("ulogin.aspx");
}
ulogin.aspx.cs
public int ValueToStore
{
get
{
return Session["ValueToStore"] != null
? (int)Session["ValueToStore"]
: 0
}
set
{
Session["ValueToStore"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = ValueToStore.ToString();
}
As you can see, you now have some code duplication between the two pages, so the next step would be to consider implementing a basepage which as the common property, and then inherit that from a1.aspx & ulogin.aspx.
i.e.
public class a1 : BasePage
{
...
}
public class ulogin : BasePage
{
...
}
public class BasePage : System.Web.Page
{
//Put ValueToStore property here.
}
There are many users visiting same page, they may set different value, and the expected result is whatever value is set by an user on Page 1 need to be displayed in Page 2.
Any Web technology is stateless as they use HTTP which is stateless again.
However there are many ways to get this done, each method has their own advantages.
--Session--
Please use session variable to store your value, which is a kind of variable.
Each user has different session variable to store, and its available
Until the user logs out (i.e. till Session is available)
Storage: Server Memory
public class Common
{
public int? Data
{
get
{
if(Session["Data"]!=null)
{
return int.Parse(Session["Data"].ToString());
}
return null.
}
set
{
Session["Data"]=value;
}
}
}
--Query String--
You can pass value from one page to another page using query string.
Page 1
int value=1;
Response.Redirect("Page2.aspx?data="+value.ToString())
Page 2
if(!string.IsNullOrEmpty(Request["data"]))
{
int value=int.Parse(Request["data"]);
}
--Posting--
You can also post the value from one page to another page.
Page 1 (html)
<form action="page2.aspx" method="post">
<input type="hidden" name="data" value="1"/>
</form>
Page 2
if(!string.IsNullOrEmpty(Request["data"]))
{
int value=int.Parse(Request["data"]);
}
There are even more ways... You have to select what is suitable for your scenario.
Read ASP.NET State management
http://msdn.microsoft.com/en-us/library/75x4ha6s.aspx
If the page ulogin.aspx is designed to be always redirected from a1.aspx, then set the PreviousPageType in ulogin.aspx and get the previous page values by this.PreviousPage instance. (Cross-Page-PostBack)
Convert member v to a property of common. Store common into a Session variable. And once you are ready to get the value, cast session variable to common and access v property from there.
I created a user control with tab container in my project. I want to access the tab container from aspx page for the reason of disable the some tabs. For example i need to hide the first tab and third tab dynamically from aspx page. Because i am using the same user control for different page. Please help me to fix this issue.
<%# Register TagPrefix="cust" TagName="Creation" Src="~/Cust_Creation.ascx" %>
<div>
<cust:Creation ID="uc_more_pack" runat="server" />
</div>
I
Add a public method on your user control which will be accessible via the page or control consuming your user control. This method can take whatever parameters you would like to determine the status of the child tab containers.
public void SetTabStatuses (bool tab1Enabled, bool tab2Enabled...){/* set status here */}
or
public void SetTabStatuses (SomeStatusEnum status) {/* set status here */}
Treat the user control as an object and the controls you've added to it should be considered fields on that object. The method(s) I suggest is allowing you to encapsulate their behavior.
Create public property on usercontrol:
Eg.
public bool ShowTab1 {get; set;}
public bool ShowTab2 {get; set;}
public bool ShowTab3 {get; set;}
public bool ShowTab4 {get; set;}
Set then from .aspx.cs page:
protected void Page_Load(object sender, System.EventArgs e)
{
usercontrol1.ShowTab1 = false;
usercontrol1.ShowTab2 = true;
usercontrol1.ShowTab3 = false;
usercontrol1.ShowTab4 = true;
}
Use the property to set the controls in UserControl:
protected void Page_Load(object sender, System.EventArgs e)
{
Tab1.Visible = ShowTab1;
Tab2.Visible = ShowTab2;
Tab3.Visible = ShowTab3;
Tab4.Visible = ShowTab4;
}
I'm approaching to Metro App world in this days, please be gentle.
Here's the problem:
a page receives a string from another page
protected override void OnNavigatedTo(NavigationEventArgs e)
{
Title.Text = e.Parameter.ToString();
}
and I need to pass this string to an User Control of the receiving page.
How can I pass a parameter from a page to an UserControl of another page?
Like this:
Add a property to your user control:
public string MyText { get; set; }
Give your user control a name.
<src:TopBarControl x:Name="MyTopBarControl" />
Then use your NavigatedTo method:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
var _TextParam = e.Parameter.ToString();
this.MyTopBarControl.MyText = _TextParam;
}
This will feed your User Control what it needs.
You could also bind to it by setting the parameter to some public property of the page. If you attempt this approach, please remember to make the User Control's property a Dependency property and not a CLR property. I wrote an article on binding if you want a better explaination http://blog.jerrynixon.com/2012/10/xaml-binding-basics-101.html
Best of luck!
Assuming usercontrol is part of navigated page, you have to do set Property of User Control on OnNavigatedTo override.
Example:
class MyUserControl : UserControl
{
public object Parameter {get;set;}
}
Suppose this user control is part of MyPage
class MyPage : Page
{
private MyUserControl myUserControl; // It is only for illustrations, Otherwise it goes to .designer.cs
protected override void OnNavigatedTo(NavigationEventArgs e)
{
Title.Text = e.Parameter.ToString();
myUserControl.Parameter = e.Parameter; // This is how to set the parameter in usercontrol.
}
}
Alright, I am trying to accomplish this: When a user clicks a button that is on a ascx web user control with text boses, it first displays a DIV that is hidden, this div contains a ascx web user control. Basically I want that web user control to grab what they typed in the boxes on the first web user control, and then apply to a SQL search from what the users type in the text boxes on the first page. Is this possible or do I need to rethink my strategy on this? I am programming in c# for the SQL statements.
It is possible.
You can define properties of the control which accepts the text input, and expose the values using direct field access, variables, or session variables; you can then use FindControl from within the newly displayed control, and, if found, utilise the now exposed properties to gather the values required.
For instance, your input control code-behind might look something like this:
partial class MyControl : UserControl
{
public string MyFieldValue
{
get { return MyFieldTextBox.Text; }
}
}
And in the next control, to use it, a little like this:
partial class MyControl : UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
var myControl = Page.FindControl("MyControlInstanceName") as MyControl;
if (myControl != null)
{
var myFieldValue = myControl.MyFieldValue;
}
}
}
Is the 2nd user control embedded in the 1st or not?
If not, you can make anything available upwards between user controls by simply adding public properties to your user controls. This means they can then be accessed from the page level or the containing user control. For example, if I have UCA, UCB, UCC
UCA contains UCB and UCC is hidden.
UCB has the following property
public string UserEnteredName
{
get { return NameTextBox.Text; }
}
UCC has the following property and method
public string UserEnteredName { get; set; }
public BindResults()
{
UserEnteredLiteral.Text = UserEnteredName;
}
Then tie it together with UCA:
protected MyButton_Click(object sender, EventArgs e)
{
UCC.UserEnteredName = UCB.UserEnteredName;
... some logic herre.
UCC.BindResults();
}
You can also raise an event from UCB that can be responded to in UCA if your button or submit action exists in UCB.