ASP.NET UserControl Uri property - asp.net

I want to pass a property of the type System.Uri to an WebControl from inside an aspx page.
Is it possible to pass the property like that:
<MyUserControl id="myusercontrol" runat="server">
<MyUrlProperty>
<System.Uri>http://myurl.com/</System.Uri>
</MyUrlProperty>
</MyUserControl>
instead of:
<MyUserControl id="myusercontrol" runat="server" MyUrlProperty="http://myurl.com/" />
which can't be casted from System.String to System.Uri
EDIT
The control is a sealed class and I don't want to modify it or write an own control. The goal is to set the url-property which is of the type System.Uri and not System.String.

To answer your actual question: no, you can't change the way you pass in the value of a property, like your example shows, without changing the code behind how that property is defined. Now on to your actual issue...
I didn't have any problem passing a string into a property of type URI on my user control and having it be auto converted from string to uri. Are you sure that the Uri you are passing in is valid? If the string you are passing in, like in a databinding scenario, wasn't properly formatted I could see this issue arising maybe.
Sample Code I used to test:
<uc1:WebUserControl ID="WebUserControl1" runat="server" MyUrlProperty="http://www.example.com" />
Code Behind:
Partial Class WebUserControl
Inherits System.Web.UI.UserControl
Public Property MyUrlProperty() As Uri
Get
Dim o As Object = ViewState("m")
If o IsNot Nothing Then
Return DirectCast(o, Uri)
Else
Return Nothing
End If
End Get
Set(ByVal value As Uri)
ViewState("m") = value
End Set
End Property
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Response.Write(MyUrlProperty)
End Sub
End Class
--Peter

Related

EnableViewState causing loss of value

Using vb.net 4.5 and Telerik 2017.2.711.45 (Q2)
I am trying to get radgrid filter expressions and a public string variable to persist across postbacks.
With EnableViewState=FALSE, radgrid filter expressions do not persist through postback, however a public string variable (stringVar) does persist.
When I set EnableViewState=TRUE the filter expressions in radgrid do persist, however it causes stringVar to not persist.
From my understanding of ViewState, it makes no sense that setting EnableViewState=TRUE would cause stringVar to not persist across postbacks. I would love to know why this is occurring and what I could do to resolve this.
EDIT:
The highlighted Line is where an error would be thrown because ReportTitle no longer has a value.
Partial Class displayxslgrid
Public ReportTitle As String
Public ReportsDB As reportDataBase
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Page.EnableViewState = True
Reports = New reportDataBase.Global_Functions(System.Web.HttpContext.Current)
End Sub
Protected Sub RadGrid1_NeedDataSource(sender As Object, e As Telerik.Web.UI.GridNeedDataSourceEventArgs) Handles RadGrid1.NeedDataSource
Call BindRadGrid1()
End Sub
Protected Sub RadGrid1_ItemCommand(ByVal source As Object, ByVal e As Telerik.Web.UI.GridCommandEventArgs) Handles RadGrid1.ItemCommand
Dim strReportTitle As String
Select Case e.CommandName
Case RadGrid.ExportToExcelCommandName, RadGrid.ExportToWordCommandName, RadGrid.ExportToCsvCommandName
strReportTitle = ReportTitle.Trim
End Select
End Sub
Public Sub BindRadGrid1()
Dim strReportTitle As String
Dim dt As DataTable = Nothing
ReportTitle = dt.Rows(0).Item("ReportTitle")
strReportTitle = dt.Rows(0).Item("ReportTitle").ToString
'RadGrid1 Data source gets set here along with other stuff
End Sub
End Class
Using view state is normal, and Telerik controls need it to preserve their values across post-backs. A public string property on your page class should not persist, and should be set/calculated every time. If you absolutely need something like that to persist, save the value in a hidden server control, or have it in the QueryString of the URL.
So it turns out, that that variable was not truly persisting. It was getting its value from the bindradgrid1. When EnableViewState=True the need data source event is not fired, therefore the bindradgrid1 is not called and the variable does not get a value. Simple fix was adding a bindradgrid1() in the item command sub so that even with EnableViewState=True, bindradgrid1() will still get called. Thanks for all who helped.

DetailsView Object Binding with Property of type Dictionary

I'm trying to bind a detailsview to an object. The object contains a property of type Dictionary which I'm having an issue with getting that bound to a combo or listbox.
I'm trying to still use AutoGenerateRows, but maybe there's a magic attribute I can put on the property to make details view see it should draw a combo box for that property.
The object to bind:
Public Class Test
Public Property MyTextboxProperty As String = "this works" 'binds fine
Public Property MyComboBoxProperty As New Dictionary(Of String, String) From {{"mykey", "myvalue"}} 'it just ignores this like it wasn't there
End Class
asp:
<asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="true" DefaultMode="Edit" DataKeyNames="">
<Fields>
</Fields>
</asp:DetailsView>
Code Behind:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
DetailsView1.DataSource = New List(Of Object) From {New Test}
DetailsView1.DataBind()
End Sub
It binds the string property fine. But it just ignores the dictionary property like it wasn't there. I can't find an example of what to add to make this work. Thanks.
Assuming that you want to display the drop down only when you allow the user to edit the DetailsView, this question may have what you are looking for, ASP.Net - DropDownList used in EditItemTemplate in DetailsView.
Basically, you will need a template field where you define the state for the normal view and the editing view. Normal view would have the selected value displayed (new property below) and the editing view would have the list of values from your Dictionary bound to the drop down. You could also select the correct value in the drop down by selecting your selected value property.
To do this you need to create a new property for the selected value:
Public Class Test
Public Property MyTextboxProperty As String = "this works" 'binds fine
Public Property MyComboBoxSelectedProperty As String = "select me" 'this would be used to bind the normal view and select the value in the edit view
Public Property MyComboBoxProperty As New Dictionary(Of String, String) From {{"mykey", "myvalue"}} 'you can bind this to the datasource of the drop down
End Class
I ended up not using the DetailsView. I could not get it to work. I did a custom control that does what I want.

Property Value gets cleared on PostBack

I have to Get and Set the BackColur of Current Page. So user can use this property from any other page
And this is my code
Private _BackgroundColour As System.Drawing.Color
Public Property MenuBackColour() As System.Drawing.Color
Get
Return _BackgroundColour
End Get
Set(ByVal value As System.Drawing.Color)
_BackgroundColour = value
End Set
End Property
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Try
NavigationMenu.BackColor = MenuBackColour
Catch ex As Exception
End Try
End Sub
But the problem is Property value gets cleared on PostBack so I'm not able to get the BackColor value from other page
On post back only the input elements are posted.
So they are the same as before the post back, what they have before the post back, have and now. So actually you do not "get" this parameters on code behind, you only "set" them and on server controls with viewstate on, you can remember this parametres on post back - but you can not change them on client side and expect to read this change on server.
Here the workaround is. Either use the viewstate of the page to save some values and keep them on post back, ether use input hidden elements to have them on post back.
If your main purpose is to retain or share the backcolor of some control between different pages, there are many ways to do it in ASP.NET. You can keep the value in cookies or sessions, or cache.
As per request, if Property must be used, I create a Default.aspx as the following:
Public Class _Default
Inherits Page
Private Shared _BackgroundColour As System.Drawing.Color = Drawing.Color.Azure
Public Shared Property MenuBackColour() As System.Drawing.Color
Get
Return _BackgroundColour
End Get
Set(ByVal value As System.Drawing.Color)
_BackgroundColour = value
End Set
End Property
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
MenuBackColour = Drawing.Color.Red
Response.Redirect("Default1")
End Sub
End Class
It will automatically be redirected to Default1.aspx, where there is a Label control in that page. It will use _Default.MenuBackColour as the label's backcolor:
Public Class Default1
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Label1.BackColor = _Default.MenuBackColour
End Sub
End Class
Again, this approach is not recommended. If Default.aspx has never been run (at least once), MenuBackColour's value may not be what you think it is. I won't encourage people to retain any static variable or property in an .aspx page for sharing.
In web applications, variable values simply get erased. But it is very simple to persist these values. They may be persisted using the Viewstate object. Before the postback is invoked, the variable's value is saved in a viewstate object. In the recieving page, the viewstate's value may be retrieved back.
//Save the value in ViewState object before PostBack
ViewState("myColour")="Black";
//Retrive the value from ViewState after the PostBack
myColourProperty=ViewState("myColour").ToString();

Concatenating string in Text or Label property

How would you concatenate a string from a resource assembly to an asterisk(*) in the Text property in an asp:Label control?
For example:
<asp:Label ID="someLabel" ...
Text="<%$ ExternalAssembly|FileName, resourceName %>*" runat="server".../>
End result is to display 'Name*'
Thanks
Reference a server-side function to return the desired string.
I apolgize, but this will be in vb.net. However, it is minimal code so I don't think it will be too hard to translate into C# if that's what you need.
Steps
Create the ASP.NET tag for the label control.
Inside the text attribute, insert a data-binding expression for the function getAssembly() . Example: Text='<%# getAssembly("Fullname")%>' We will build this function in a moment. Also note that it accepts a parameter to identify what piece of information you need regarding the assembly. Another common mistake is not using single quotes for the inline expression (because double quotes will conflict with the string parameter).
Import the necessary namespaces System and System.Reflection into the code-behind.
Create the function getAssembly(ByVal InfoItem as String) in the code-behind (details for this function are below).
Add a line in the Sub Page_Load() to bind data to the assemblyLabel control when the page is loaded.
Here is the necessary code in detail for each step:
ASP.NET Tag
<asp:Label ID="assemblyLabel" runat="server" Text='<%# getAssembly("Fullname")%>'></asp:Label>
Function in the Code-Behind
Public Function getAssembly(ByVal InfoItem As String) As String
Dim a As AssemblyName = Assembly.GetExecutingAssembly.GetName()
Select Case InfoItem
Case "Name"
Return a.Name
Case "Fullname"
Return a.FullName
Case "Version"
Return a.Version.ToString
Case Else
Return ""
End Select
End Function
Necessary imports:
Imports System
Imports System.Reflection
Bind the data in Page_Load:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
assemblyLabel.DataBind()
End Sub
The entire code-behind...
Imports System
Imports System.Reflection
Public Class WebForm1
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
assemblyLabel.DataBind()
End Sub
Public Function getAssembly(ByVal InfoItem As String) As String
Dim a As AssemblyName = Assembly.GetExecutingAssembly.GetName()
Select Case InfoItem
Case "Name"
Return a.Name
Case "Fullname"
Return a.FullName
Case "Version"
Return a.Version.ToString
Case Else
Return ""
End Select
End Function
End Class

Populate TextBox From Public Property From Code-Behind

I am trying to use a property from the code-behind to populate a textbox instead of using in the code-behind textbox.text=. I am using vb.net. Here is the code for the aspx page:
<asp:Content ID="Content2" ContentPlaceHolderID="MainContentPlaceHolder" runat="server">
<asp:TextBox runat="server" ID="roleTextBox" Text='<%# CurrentRole.Name%>'></asp:TextBox>
</asp:Content>
Here is the code behind code:
Imports Compass.UI.components
Imports Compass.Core.Domain
Imports Compass.Core.Domain.Model
Namespace app.administration.Roles
Partial Public Class edit
Inherits ClaimUnlockPage
Private _roleRepository As IRoleRepository
Private _roleId As Integer
Private _role As Role
Public Property CurrentRole() As Role
Get
Return _role
End Get
Set(ByVal value As Role)
_role = value
End Set
End Property
Public Property RoleRepository() As IRoleRepository
Get
Return _roleRepository
End Get
Set(ByVal value As IRoleRepository)
_roleRepository = value
End Set
End Property
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
LoadRole()
End Sub
Private Sub LoadRole()
_roleId = Config.RequestVal("id", Request)
_role = _roleRepository.GetById(_roleId)
End Sub
End Class
End Namespace
When I run the page the text box is empty.
I didn't see roleTextBox.text=value in your code! in LoadRole or anywhere.
And if you try to bind it, you need a static class for Role.
Just for testing try to add the following line in LoadRole
Private Sub LoadRole()
_roleId = Config.RequestVal("id", Request)
_role = _roleRepository.GetById(_roleId)
roleTextBox.text =CrrentRole.Name;
End Sub
if the roleTextBox is still empty then the CurrentRole.Name is empty.
As far as I know you can't bind a property of a control like this (I wish you could but I've never been able to figure out or find an example how to). The way I've always done it is create a protected function to return e.g.
Protected Function GetCurrentRoleName() As String
Return CurrentRole.Name
End Function
And in your markup bind like so
Text='<%# GetCurrentRoleName() %>'
You have to DataBind the container-control which contains your Textbox(f.e. a GridView,UserControl,etc.). So at least your aspx-page must be databound.
"When called on a server control, this method resolves all data-binding expressions in the server control and in any of its child controls."
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Me.CurrentRole = New Role("Administrator")
Me.DataBind() '!!!!!!!
End Sub
Private _currentRole As Role
Protected Property CurrentRole() As Role
Get
Return _currentRole
End Get
Set(ByVal value As Role)
_currentRole = value
End Set
End Property
Public Class Role
Public Sub New(ByVal name As String)
Me.Name = name
End Sub
Public Name As String
End Class
Then you can use your aspx-code to set the TextBox'-text property.

Resources