What I'm trying to do is send a string from ASPX to the code behind of a UserControl.
The first step works, and calls a WS and brings back a string.
ASPX
function (data) {
//UpdateUserControl!
};
The issue is that I have no idea how to pass this string on to a UserControl, I tried a __doPostBack but that only refreshes the whole page. I just want to update a listbox with the items. With the intention of later retrieving a string from the User Control. I am using a UpdatePanel in my UserControl.
ASCX.VB
'Get shopping list
Public Function UpdateList(list As String) As ListBox
Dim result As String = ""
Dim strItems As String = list
Dim strArray As String() = strItems.Split(","c)
For Each item As String In strArray
myListBox.Items.Add(item)
Next
Return email_add
End Function
Add a property to the code behind of the usercontrol. You can then set the value from the containing page.
Use this code,
In aspx
public string yourvalue { get; set; }
then ascx.cs
_Default d = new _Default();
string s = d.yourvalue;
sure its working.
Related
Asp.Net 4.0
Is it possible to call a function in a user control from the parent page in code behind?
The user controls are created by other programmers, however each will have a common public function that i look for called "Output" which returns values in need for the main page. The main page has a main menu, so only one user control will display based upon the main menu selection.
Folder in WebApp with user controls:
> UserControls
ProductA.ascx
ProductB.ascx
ProductC.ascx
ProductD.ascx
etc...
Code behind when user clicks a menu button:
Dim product As string = Session("MenuProduct")
Dim uc As UserControl
uc = LoadControl("~/UserControls/" & product & ".ascx")
InputPanel.Controls.Add(uc)
Function in user control I would like to access. This will be a common Function.
Public Function Output(ByVal ParamArray expr() As Object) As Object
...code
End Function
You can call functions in a userControl from a parent page if they have the right access modifier. Public I believe
Dim product As string = Session("MenuProduct")
Dim uc As UserControl
uc = LoadControl("~/UserControls/" & product & ".ascx")
InputPanel.Controls.Add(uc)
if (uc is TypeWithMethod )
{
Dim ucTyped As TypeWithMethod
ucTyped = uc As TypeWithMethod
ucTyped.Method()
}
Vb syntax is rusty, kept putting ; after every line.
Here are little details to what andrew is talking about...
Public Interface IGroupable
Function GetGroupId() As Int32
End Interface
Class MyUserControl
Inherits UserControl
Implements IGroupable
Public Function GetGroupId() As Integer Implements IGroupable.GetGroupId
Return 1
End Function
End Class
Class MyPage
Inherits Page
Dim id As Int32 = DirectCast(myUserControl, IGroupable).GetGroupId()
End Class
So basicly create a Interface, have all of your user controls implement that interface, and then when you load any of your user controls within webpage...simply CAST them to the the type of your interface name....your interface will have the access to the function.
What i'm doing is creating a website where the design is done i html files that are then read into the masterpage using System.IO.StreamReader.
and inside the html templates there are keywords like #USER.LOGIN#
that I replace with functions etc.
The issue is that i'm replacing #USER.LOGIN# With a usercontrol where there is a login form.
I have a function that reads the usercontrol into a string and it works.
but since the usercontrol is loaded to string alle the events are not following.
so when I submit the login form nothing nothing happends (the page posts) but cannot get any of the fields from the form...
NOTE:
i'm using url-rewriting so urls are http://www.domain.com/account/login
where account is account.aspx and login is the mode the account is in.
Code for replacing the keyword in the streamreader loop (pr line)
If InStr(line, "#USER.LOGIN#") Then
line = line.Replace("#USER.LOGIN#", vbCrLf & userfunc.GetMyUserControlHtml("uc", "account_login.ascx", "/account/login/") & vbCrLf)
End If
And the functions to read usercontrol
Public Shared Function GetMyUserControlHtml(contextKey As String, controllerfile As String, Optional ByVal formaction As String = "")
Dim myId As Guid = New Guid()
Return userfunc.RenderUserControl("~\Controllers\" & controllerfile, "", myId, formaction)
End Function
Public Shared Function RenderUserControl2(path As String, Optional ByVal formaction As String = "") As String
Using pageHolder As New Page(), _
viewControl As UserControl = DirectCast(pageHolder.LoadControl(path), UserControl), _
output As New StringWriter(), _
tempForm As New HtmlForm()
If formaction <> "" Then
tempForm.Action = formaction
Else
tempForm.Action = HttpContext.Current.Request.RawUrl
End If
tempForm.Controls.Add(viewControl)
pageHolder.Controls.Add(tempForm)
HttpContext.Current.Server.Execute(pageHolder, output, False)
Dim outputToReturn As String = output.ToString()
Return outputToReturn
End Using
End Function
How would you guyz do this?
I need the userlogin to be hardcoded in the usercontrol but still be able to place it anywhere using the template keyword.
This will also be used with other functions (newsletter signup, shoutbox etc.)
what i would suggest is register you control on the web config..
<add tagPrefix="CustomControl" tagName="LogIn" src="~/UserControls/Login.ascx"/>
you can still use "#USER.LOGIN#" but instead of replacing it with a control...
replace it with a something like this
<CustomControl:LogIn id="LogIn" runat="server"/>
this is just a quick write up.. but you could always try if it works
you can save your HTML like this istead of placing an actual "#USER.LOGIN#"
<% =GetLoginControl() %>
and then create a public function in your code behind named GetLoginControl() and return a response.write of the HTML Mark up you need
on my website I have an "Enroll" page where users submit some basic information, there's some basic validation on that page then the user is taken to an "Enrollment Confirmed" page (which i don't want to display the info from previous page). On the confirmation page there is link to a "Print Enrollment Confirmation" page which, on this page, I want to contain the information entered from the "Enroll" page. So basically, I want the input entered on "Page 1" put into labels on "Page 3". I've seen some examples of transferring information from "Page 1" to "Page 2" but I have an extra page users need to go through before hitting the page with their previously entered data.
Can someone give me an explanation on how I could do this without using query strings? Thank you.
You could create an class with properties for each form field then store it in the session. Then after you populate what you need on page 3 remove it from the session.
Example
Class:
<Serializable()>
Public Class Input
Private _FirstName As String = String.Empty
Private _LastName As String = String.Empty
Public Property FirstName As String
Get
Return _FirstName
End Get
Set(ByVal value As String)
_FirstName = value
End Set
End Property
Public Property LastName As String
Get
Return _FirstName
End Get
Set(ByVal value As String)
_FirstName = value
End Set
End Property
Public Sub New()
End Sub
End Class
Storing data:
Private Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
Dim FormData As New Input()
FormData.FirstName = txtFirstName.Text
FormData.LastName = txtLastName.Text
Session("InputData") = FormData
End Sub
Retrieving it:
If Not IsNothing(Session("InputData")) Then
Dim FormData As Input = DirectCast(Session("InputData"), Input)
txtFirstName.Text = FormData.FirstName
txtLastName.Text = FormData.LastName
Session.Remove("InputData")
End If
You could use the button.postbackurl property to post the data to another page:
http://msdn.microsoft.com/en-us/library/ms178140.aspx
In the intermediary pages, you could store the data in hidden fields from page 1, so the data would be in the posted results for page 3, when another button posts the data from page 2 to page 3.
HTH.
This pretty much sums up your choices:
http://msdn.microsoft.com/en-us/library/6c3yckfw.aspx
I would store the values in hidden input fields on page 2 and if page 3 is called as a form submit, then the values will be available through Request.Form.
Anyone know of a smooth way to get all of the selected items in a listbox control by using extension methods?
And, please, spare me the argument of it's irrelevant as to how one gets such a list because in the end everything uses a loop to iterate over the items and find the selected ones anyway.
var selected = yourListBox.Items.GetSelectedItems();
//var selected = yourDropDownList.Items.GetSelectedItems();
//var selected = yourCheckBoxList.Items.GetSelectedItems();
//var selected = yourRadioButtonList.Items.GetSelectedItems();
public static class Extensions
{
public static IEnumerable<ListItem> GetSelectedItems(
this ListItemCollection items)
{
return items.OfType<ListItem>().Where(item => item.Selected);
}
}
Extension method:
public static List<ListItem> GetSelectedItems(this ListBox lst)
{
return lst.Items.OfType<ListItem>().Where(i => i.Selected).ToList();
}
You can call it on your listbox like:
List<ListItem> selectedItems = myListBox.GetSelectedItems();
You could also do the conversion using a 'Cast' on the list box items like:
return lst.Items.Cast<ListItem>().Where(i => i.Selected).ToList();
Not sure which will perform better OfType or Cast (my hunch is Cast).
Edit based on Ruben's feedback for a generic ListControl method which would indeed make it much more useful extension method:
public static List<ListItem> GetSelectedItems(this ListControl lst)
{
return lst.Items.OfType<ListItem>().Where(i => i.Selected).ToList();
}
Hello i've created one solution for this problem in this post using VB.NET:
Getting all selected values from an ASP ListBox
This code below is the same as the link above:
Public Shared Function getSelectedValuesFromListBox(ByVal objListBox As ListBox) As String
Dim listOfIndices As List(Of Integer) = objListBox.GetSelectedIndices().ToList()
Dim values As String = String.Empty
For Each indice As Integer In listOfIndices
values &= "," & objListBox.Items(indice).Value
Next indice
If Not String.IsNullOrEmpty(values) Then
values = values.Substring(1)
End If
Return values
End Function
I hope it helps.
Im making a site in Visual Studio using vb and I have a variable in page_load but need its value in the event handler of a button for passing on session.
Any suggestions on how I can do this? Any help is appreciated
You can store a value in the CommandArgument property of a Button:
btn.CommandArgument = "Your value"
And then when handling the event you can pull it out:
CType(sender, Button).CommandArgument
You could also make a new class that extends Button and create new properties like below if you need multiple arguments:
Class SessionButton
Inherits Button
Public Property SessionGUID() As Guid
Get
Dim s As Guid = Nothing
If Not String.IsNullOrEmpty(ViewState("SessionGUID")) Then
s = New Guid(ViewState("SessionGUID").ToString())
End If
Return s
End Get
Set(ByVal value As Guid)
ViewState("SessionGUID") = value.ToString()
End Set
End Property
End Class
couldn't you just make the variable a class scoped variable, instead of local?
You can store it in a viewstate backed property:
Public Property MyStringVar() As String
Get
If ViewState("MyStringVar") = Nothing Then
Return String.Empty
End If
Return ViewState("MyStringVar").ToString()
End Get
Set
ViewState("MyStringVar") = value
End Set
End Property
Now using this property you can save your variable on page load and access it in the button click event handler.
EDIT: updated to VB
you declare the variable outside the page_load and then you can use it where you want :)
You could also create a class that encapsulates the action. Then you can capture any data you want and easily add to it later.
void Page_Load()
{
myBtn.Click += new MyButtonClass(variable).Run;
}
class MyButtonClass
{
int Param;
MyButtonClass(int param)
{
Param = param;
}
public void Run(object sender, EventArgs args)
{
// Do something usefull
}
}
If the data is created/retrieved on every Page_Load, this will work. If it is wrapped around an (! IsPostBack), the data must be stored in a session. Fortunatly, the class can be easily modified to store/load the variable from a session parameter.
I'm sorry for the c# code, maybe someone else can translate it then remove this message?