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.
Related
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.
I've search a lot for this issue but nothing came up.
My problem is the following: I have a main view in which I want to load a user control with parameters when I click on a button but the user control won't show. The constructor of the user control is called and the parameters are set, even the page load event from the user control is called. What am i doing wrong?
Main.aspx:
<%# Page Title="Main page" Language="C#" AutoEventWireup="true" CodeBehind="Main.aspx.cs" Inherits="MainApp.Main" MasterPageFile="~/Site.master" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent"></asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<%-- some other fields which i send to the user control on click --%>
<div class="col-lg-1 col-sm-12 col-md-1">
<asp:Button runat="server" CssClass="btn btn-primary" CausesValidation="false" ID="generateData" OnClick="generateData_Click" Text="View info" />
</div>
<div runat="server" id="contentDiv">
<p>No info available atm.</p>
</div>
</asp:Content>
Main.aspx.cs button click event:
protected void generateData_Click(object sender, EventArgs e)
{
UserControl1 uc = (UserControl1 )this.LoadControl(typeof(UserControl1 ), new object[] { param1, param2, param3});
contentDiv.Controls.Clear();
contentDiv.Controls.Add(uc);
}
UserControl1.aspx.cs:
public partial class UserControl1: System.Web.UI.UserControl
{
public string Param3 { get; set; }
public string Param1 { get; set; }
public string Param2 { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
Page.DataBind();
}
public UserControl1(string param1, string param2, string param3)
{
Param1 = param1;
Param2 = param2;
Param3 = param3;
}
}
UserControl1.ascx:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="UserControl1.ascx.cs" Inherits="MainApp.UserControls.UserControl1" %>
<div>
<p style="color: red">Under construction</p>
</div>
The user control isn't visible on the main page and I don't know why.
PS: I know that i can send parameters as seen below but I don't understand why I cannot use the method described above.
UserControl1 uc = (UserControl1)this.LoadControl("~/UserControls/UserControl1.ascx");
uc.Param1 = "val1";
...
Here is the full explanation of why second method with LoadControl by type will not work: Asp.net Usercontrol LoadControl Issue.
The reason there is a difference is because in the second instance you
are bypassing the binding mechanism of the the two partial classes.
When you include the ascx control in the page as a normal declaration,
the controls declared within it (the label in your example) are
automatically instantiated by the framework as the class is
instantiated. This is a binding mechnism that reads the "front-end"
ascx file and instantiates objects in the class.
When you use LoadControl(string) - you are doing exactly the same
thing.. it uses a virtual path to get the "front-end" file and ensure
controls within it are instantiated.
However, when you use the new (to 2.0) LoadControl(type, object)
version, there is no virtual path available and it rightly so makes no
assumptions (as it cannot ensure that a type has a front end file).
I have declared a class but when I try to access it's members I get the following error :
DataBinding: 'reapTest.Toop' does not contain a property with the name 'Rang'.
WebForm1.aspx.cs :
namespace reapTest {
public class Toop {
public string Rang;
public int Gheymat;
}
public static class MyData {
public static Toop[] TP = new Toop[] { new Toop() { Rang = "Ghermez", Gheymat = 100 }, new Toop() { Rang = "Yellow", Gheymat = 44 } };
public static Toop[] RT() {
return TP;
}
}
public partial class WebForm1 : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
}
}
}
WebForm1.aspx :
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="reapTest.WebForm1" %>
<!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="Repeater1" runat="server" DataSourceID="ObjectDataSource1">
<ItemTemplate>
<%#Eval("Rang")%>
</ItemTemplate>
</asp:Repeater>
<asp:ObjectDataSource runat="server" ID="ObjectDataSource1" SelectMethod="RT" TypeName="reapTest.MyData"></asp:ObjectDataSource>
</div>
</form>
</body>
</html>
I believe it is because it is looking for a literal property named Rang. You have a field named Rang, but that's not the same as a property, to-wit:
EDIT: Code sample
public class Toop {
// These values are *fields* within the class, but *not* "properties."
private string m_Rang; // changing these field decls to include m_ prefix for clarity
private int m_Gheymat; // also changing them to private, which is a better practice
// This is a public *property* procedure
public string Rang
{
get
{
return m_Rang;
}
set
{
m_Rang = value;
}
}
}
Fields and Properties are related in that Properties provide a public "wrapper" mechanism to the "private" field data of each instance of the class. But it is critical to note that they are separate concepts, and not interchangeable. Merely having a field declaration (also called a member in some object parlance) does not expose it as a property. Note what #FrédéricHamidi said - the docs state the "value of the expression parameter must evaluate to a public **property**"(emphasis mine).
As noted in this excerpt directly from Microsoft, EVAL, one way or the other, has to have a property.
Hopefully that helps.
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#";
}
}
}
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.