ASP.Net Declaratively Passing Value from Page Property to User Control - c#

I need to find a way to declaratively (not in the code behind file) pass the value of a property in an ASP.Net web page to a user control. Following is a simple example of what I'm trying to do, but I can't get it to work.
Here is the markup for the aspx page where I'm creating an object of the user control:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%# Register Src="~/MyUserControl.ascx" TagName="MyUserControl" TagPrefix="uc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<uc1:MyUserControl ID="MyUserControl1" runat="server"
UserControlProperty = '<%# Bind("PageProperty") %>' />
</div>
</form>
</body>
</html>
Here is the code behind (aspx.cs) file from the aspx page:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
public int PageProperty { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
PageProperty = 42;
}
}
Here is the markup from the usercontrol (ascx file):
<%# Control Language="C#" AutoEventWireup="true"
CodeFile="MyUserControl.ascx.cs" Inherits="MyUserControl" %>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
And here is the code behind file (ascx.cs) from the user control:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class MyUserControl : System.Web.UI.UserControl
{
public int UserControlProperty { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
TextBox1.Text = UserControlProperty.ToString();
}
}
So, all I'm trying to do is pass the value of the PageProperty property defined in the aspx page into the user control to set it's UserControlProperty, and then display that value in a textbox in the usercontrol. Can anyone tell me what I've done wrong here?

try
UserControlProperty = '<%= this.PageProperty %>'
or consider reading: http://support.microsoft.com/kb/307860#1b
there's such a thing as Page.DataBind() and Control.DataBind(). I'm not quite sure if you should call them explicitly, but it might be the case...
if you still want your case, you can try to do it through string:
public string UserControlProperty { get; set; }
it perfectly works.

I would recommend taking a look at this article.
It shows you how to create your own ExpressionBuilder to parse C# anywhere in your markup without having to DataBind or jump through any other hoops.

Related

Parser Error when retrieving form posted data in C#

Trying to retrieve posted data from HTML form into C# page.
However I am receiving this error:
Parser Error
Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.
Parser Error Message: 'Ass2.CarPage' is not allowed here because it does not extend class 'System.Web.UI.Page'.
Source Error:
Line 1: <%# Page Language="C#" AutoEventWireup="true" CodeBehind="CarPage.aspx.cs" Inherits="Ass2.CarPage"%>
Line 2:
Line 3:
HTML Code:
<!--Car Search Form-->
<div id="Search_Form">
<form name="Car Search" action="CarPage.aspx" method="post">
<h1 align="center">Search For A Car Now: </h1>
<h2 align="center">
<select name="Car">
<option value="Volvo">Volvo</option>
<option value="Ford">Ford</option>
<option value="Mercedes">Mercedes</option>
<option value="Audi">Audi</option>
<option value="Vauxhall">Vauxhall</option>
</select>
<h1 align="center">
<input type="Submit" value="Submit">
</h1>
</form>
</div>
C# Code:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="CarPage.aspx.cs" Inherits="Ass2.CarPage"%>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<%
if (Request.Form["Car"] == "Volvo")
{
Response.Redirect("VolvoHomepage.html");
}
if (Request.Form["Car"] == "Ford")
{
Response.Redirect("FordHomepage.html");
}
if (Request.Form["Car"] == "Mercedes")
{
Response.Redirect("MercedesHomepage.html");
}
if (Request.Form["Car"] == "Audi")
{
Response.Redirect("AudiHomepage.html");
}
if (Request.Form["Car"] == "Vauxhall")
{
Response.Redirect("VauxhallHomepage.html");
}
%>
</body>
</html>
ASPX.CS Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
}
The error indicates that you have a class Ass2.CarPage that is not inheriting from System.Web.UI.Page. The class that it found was likely the class in the designer file, which is only a partial class definition and so doesn't have the inheritance declared there.
The actual code behind file had the wrong namespace and class, so it wasn't picked up. By changing it from WebApplication2.WebForm to Ass2.CarPage the partial classes now are referring to the same time and thus get "merged", and since your code behind inherits from the correct class, it all works.
On a side note, you should take the inline C# code out of of your ASPX page and put it in the Page_Load method of your code behind. It's silly to mix C# into the ASPX page when that's what the code behind is intended for.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Form["Car"] == "Volvo")
{
Response.Redirect("VolvoHomepage.html");
}
else if (Request.Form["Car"] == "Ford")
{
Response.Redirect("FordHomepage.html");
}
else if (Request.Form["Car"] == "Mercedes")
{
Response.Redirect("MercedesHomepage.html");
}
else if (Request.Form["Car"] == "Audi")
{
Response.Redirect("AudiHomepage.html");
}
else if (Request.Form["Car"] == "Vauxhall")
{
Response.Redirect("VauxhallHomepage.html");
}
}
}
}
Also, you should probably make sure the form values exist before accessing them. But I'll leave that as an exercise for you.

Reading rss2 feed using C# ASP.NET content:encoded tag

I am trying to read a rss2 feed from a Word Press blog. I have found examples of this, including the one I adapted for my code here. The problem is that it does not read the content:encoded tag. I have searched and found other people that have had this problem, but nothing where it seems to have been solved.
I am using a repeater on an asp.net page with C# code behind to display the data.
The problem seems to be that the content:encoded tag is not defined in http://purl.org/dc/elements/1.0/modules/content/ I've checked it's not listed there at all. When I set a breakpoint and check the value the "content" is actually getting the value of another tag: "{0}" is the value in it after the first post is read into the post object. Although it is never displayed in the repeater.
I assume that content must have been defined at that URL at one time, because this supposedly worked at one time. But it does not now.
Short of reading the XML as a string and re-inventing the wheel to read the tags is there a known way to solve this? Is there a link I can supply that will define the content tag for the code to use? (I am assuming that is the purpose of the URLS). Could I just create my own page with a definition?
Here is the code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Linq;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Load the blog posts
string sURL1 = "http://www.stellman-greene.com/feed";
string sURL2 = "http://arnottsuspension.com/?feed=rss2";
XDocument ourBlog = XDocument.Load(sURL2);
// Query the <item>s in the XML RSS data and select each one into a new Post()
IEnumerable<Post> posts =
from post in ourBlog.Descendants("item")
select new Post(post);
postRepeater.DataSource = posts;
postRepeater.DataBind();
}
class Post
{
public string Title { get; private set; }
public DateTime? Date { get; private set; }
public string Url { get; private set; }
public string Description { get; private set; }
public string Creator { get; private set; }
public string Content { get; private set; }
private static string GetElementValue(XContainer element, string name)
{
if ((element == null) || (element.Element(name) == null))
return String.Empty;
return element.Element(name).Value;
}
public Post(XContainer post)
{
// Get the string properties from the post's element values
Title = GetElementValue(post, "title");
Url = GetElementValue(post, "guid");
Description = GetElementValue(post, "description");
Creator = GetElementValue(post,
"{http://purl.org/dc/elements/1.1/}creator");
Content = GetElementValue(post,
"{http://purl.org/dc/elements/1.0/modules/content/}encoded");
// The Date property is a nullable DateTime? -- if the pubDate element
// can't be parsed into a valid date, the Date property is set to null
DateTime result;
if (DateTime.TryParse(GetElementValue(post, "pubDate"), out result))
Date = (DateTime?)result;
}
public override string ToString()
{
return String.Format("{0} by {1}", Title ?? "no title", Creator ?? "Unknown");
}
}
}
Here is the HTML/ASP:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Repeater ID="postRepeater" runat="server">
<ItemTemplate>
<tr>
<td><%# Eval("Title") %></td><br />
</tr>
<tr>
<td><%# Eval("Description") %></td><br />
</tr>
<tr>
<td><%# Eval("Content") %></td><br />
</tr>
<tr>
<td>Read More</td><br /><br />
</tr>
</ItemTemplate>
</asp:Repeater>
</div>
</form>
</body>
</html>
I found the correct namespace (If that is the correct term to use for this.
Where I had:
http://purl.org/dc/elements/1.0/modules/content/
I replaced it with:
http://purl.org/rss/1.0/modules/content/
And it now works.

How to avoid hard-coding the Reference for a UserControl?

I'd like to know whether or not there is a dynamic way to avoid hard-coding the Reference for a UserControl or by "USING"?
<%# Reference Control="~/UserControl.ascx" %>
using UserControl;
I'm seeking a way to dynamically add References to UserControls to the page from code behind.
If I have understood your question correctly, this should do what you want to do-
Default.aspx
<!DOCTYPE html>
<html>
<head runat="server">
<title>Dynamic User Control Test</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h1>Dynamic User Control Test</h1>
<asp:PlaceHolder ID="UserControlPlaceHolder" runat="server"></asp:PlaceHolder>
</div>
</form>
</body>
</html>
Default.aspx.cs
using System;
using System.Web.UI;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
UserControl uc = Page.LoadControl("~/UserControl.ascx") as UserControl;
if (uc != null)
{
UserControlPlaceHolder.Controls.Add(uc);
}
}
}
UserControl.ascx
<%# Control Language="C#" AutoEventWireup="true" CodeFile="UserControl.ascx.cs" Inherits="UserControl" %>
<p>Here is some content inside the user control</p>
UserControl.ascx.cs (this isn't needed if the UserControl is static and contains no solution specific code)
using System;
public partial class UserControl : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
This will only work with controls that are dynamically added to the page though.

Advice on how to create a common base class (or functionality) between a page and master?

I created a custom base class that my .aspx pages inherit from.
Since Master page's inherit from MasterPage and not Page, how can I create common functionality that are available in both my Pages and Master pages?
public class SitePage : System.Web.UI.Page
{
public SitePage()
{
}
public bool IsLoggedIn
{
//
}
public string HtmlTitle
{
//
}
}
One approach would be to put all the functionality in the Master page and always call them by going through the Master page. You can strongly type the Master property in SitePage:
public class SitePage : Page
{
public new MyMaster Master { get { return base.Master as MyMaster; } }
}
Then access the values through the Master:
this.Master.IsLoggedIn
Master Page:
<%# Master Language="C#" AutoEventWireup="true" CodeBehind="MyProject.master.cs"
Inherits="MyProject.MasterPages.MyProject" %>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
Base page:
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPages/MyProject.Master"
AutoEventWireup="true" CodeBehind="BasePage.aspx.cs"
Inherits="MyProject.BasePage" %>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1"
runat="server">
</asp:Content>
Content Page:
<%# Page Title="MyProject - Home" Language="C#"
MasterPageFile="~/MasterPages/MyProject.Master" AutoEventWireup="true"
CodeFileBaseClass="MyProject.BasePage" CodeFile="Default.aspx.cs"
Inherits="MyProject.Default"
Meta_Description="Code Snippet: Master Page and Base Page"
Meta_Keywords="master, base, content" Theme="Style" %>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1"
runat="server">
</asp:Content>

how to call a variable in code behind to aspx page

i know i have seen this but cant recall the correct way of doing it... basically i have a string variable called "string clients" in my .cs file.. but i wasn't to be able to pass it to my aspx page something like
<%=clients%>
please correct me, i do not recall or not sure how to do this. (new to c#) and when i googled it.. it was not clear.. or not many of these out there.. searched as
"asp.net c# <%= %> not consistent results.. maybe because i do not know how to call these..
The field must be declared public for proper visibility from the ASPX markup. In any case, you could declare a property:
private string clients;
public string Clients { get { return clients; } }
UPDATE: It can also be declared as protected, as stated in the comments below.
Then, to call it on the ASPX side:
<%=Clients%>
Note that this won't work if you place it on a server tag attribute. For example:
<asp:Label runat="server" Text="<%=Clients%>" />
This isn't valid. This is:
<div><%=Clients%></div>
In your code behind file, have a public variable
public partial class _Default : System.Web.UI.Page
{
public string clients;
protected void Page_Load(object sender, EventArgs e)
{
// your code that at one points sets the variable
this.clients = "abc";
}
}
now in your design code, just assign that to something, like:
<div>
<p><%= clients %></p>
</div>
or even a javascript variable
<script type="text/javascript">
var clients = '<%= clients %>';
</script>
For
<%=clients%>
to work you need to have a public or protected variable clients in the code-behind.
Here is an article that explains it:
http://msdn.microsoft.com/en-us/library/6c3yckfw.aspx
Make sure that you have compiled your *.cs file before browsing the ASPX page.
First you have to make sure the access level of the variable is protected or public. If the variable or property is private the page won't have access to it.
Code Behind
protected String Clients { get; set; }
Aspx
<span><%=Clients %> </span>
You need to declare your clients variable as public, e.g.
public string clients;
but you should probably do it as a Property, e.g.
private string clients;
public string Clients{ get{ return clients; } set {clients = value;} }
And then you can call it in your .aspx page like this:
<%=Clients%>
Variables in C# are private by default. Read more on access modifiers in C# on MSDN and properties in C# on MSDN
You can access a public/protected property using the data binding expression <%# myproperty %> as given below:
<asp:Label ID="Label1" runat="server" Text="<%#CodeBehindVarPublic %>"></asp:Label>
you should call DataBind method, otherwise it can't be evaluated.
public partial class WebForm1 : System.Web.UI.Page
{
public string CodeBehindVarPublic { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
CodeBehindVarPublic ="xyz";
//you should call the next line in case of using <%#CodeBehindVarPublic %>
DataBind();
}
}
I would create a property to access the variable, like this:
protected string Test
{
get; set;
}
And in your markup:
<%= this.Test %>
The HelloFromCsharp.aspx look like this
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="HelloFromCsharp.aspx.cs" Inherits="Test.HelloFromCsharp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<p>
<%= clients%>
</p>
</form>
</body>
</html>
And the HelloFromCsharp.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Test
{
public partial class HelloFromCsharp : System.Web.UI.Page
{
public string clients;
protected void Page_Load(object sender, EventArgs e)
{
clients = "Hello From C#";
}
}
}

Categories

Resources