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#";
}
}
}
Related
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.
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.
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 am trying to get POST data, but I'm having no luck. My code is below. When I click the form button nothing happens.
I expected at least my IDE to snap at A.Ret(), but nothing happens whatsoever.
File Test.cs
using System.Web;
public class A
{
public static string ret() {
var c = HttpContext.Current;
var v = c.Request.QueryString; // <-- I can see get data in this
return c.Request.UserAgent.ToString();
return c.Request.UserHostAddress.ToString();
return "woot";
}
}
File Default.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="aspnetCSone._Default" %>
<!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>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server" method="post" action="Default.aspx">
<input type=hidden name="AP" value="99" />
<input type=button value="Submit" />
<div>
<a id="aa">a</a>
<% = A.ret() %>
</div>
</form>
</body>
</html>
Try using:
string ap = c.Request["AP"];
That reads from the cookies, form, query string or server variables.
Alternatively:
string ap = c.Request.Form["AP"];
to just read from the form's data.
c.Request["AP"] will read posted values. Also you need to use a submit button to post the form:
<input type="submit" value="Submit" />
instead of
<input type=button value="Submit" />
I'm a little surprised that this question has been asked so many times before, but the most reuseable and friendly solution hasn't been documented.
I often have webpages using AngularJS, and when I click on a Save button, I'll "POST" this data back to my .aspx page or .ashx handler to save this back to the database. The data will be in the form of a JSON record.
On the server, to turn the raw posted data back into a C# class, here's what I would do.
First, define a C# class which will contain the posted data.
Supposing my webpage is posting JSON data like this:
{
"UserID" : 1,
"FirstName" : "Mike",
"LastName" : "Mike",
"Address1" : "10 Really Street",
"Address2" : "London"
}
Then I'd define a C# class like this...
public class JSONRequest
{
public int UserID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
}
(These classes can be nested, but the structure must match the format of the JSON data. So, if you're posting a JSON User record, with a list of Order records within it, your C# class should also contain a List<> of Order records.)
Now, in my .aspx.cs or .ashx file, I just need to do this, and leave JSON.Net to do the hard work...
protected void Page_Load(object sender, EventArgs e)
{
string jsonString = "";
HttpContext.Current.Request.InputStream.Position = 0;
using (StreamReader inputStream = new StreamReader(this.Request.InputStream))
{
jsonString = inputStream.ReadToEnd();
}
JSONRequest oneQuestion = JsonConvert.DeserializeObject<JSONRequest>(jsonString);
And that's it. You now have a JSONRequest class containing the various fields which were POSTed to your server.
The following is OK in HTML4, but not in XHTML. Check your editor.
<input type=button value="Submit" />
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.