Why DataBinding can't find a property which exist? - c#

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.

Related

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.

Access ASPX elements inside classes

I have a bunch of methods which manipulate the ASPX page elements and at this point it makes sense to encapsulate them into their own static object. However, it seems like I do not have access into the form elements outside of the ASPX page. Any ideas on how to go about this?
You need to pass the Page itself into the class, see the example below:
ASPX page
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtTest" runat="server" Text="Test" />
</div>
</form>
Code-Behind
protected void Page_Load(object sender, EventArgs e)
{
Process p = new Process(this);
string s = p.GetTextBoxValue();
}
Class
public class Process
{
public Page thePage { get; set; }
public Process(Page page)
{
thePage = page;
}
public string GetTextBoxValue()
{
TextBox tb = (TextBox)thePage.FindControl("txtTest");
return tb.Text;
}
}
Process is probably not the best name for the class, but this is purely a demo.
Also, passing the Page object into another class tight couples that class to the Page object. I would recommend reconsidering your design of the class you're trying to make to not rely on the Page object entirely.
If you really want to encapsulate functionality, I guess you best create a class in which you pass the relevant elements to the constructor.
If you are aiming on reuse in other pages, you could create a base page from which you inherit. Another option is to do stuff in a master page that you refer from your pages.
I think a more detailed question is required to give a more detailed answer.
You need to pass Page object as one of the parameters to your class methods, this way its elements will be accessible inside the class.
For example if you have a class like:
public class CMyDataClass {
public bool CompareText(System.Web.UI.Page i_oPage) {
TextBox oTextBox = i_oPage.FindControl("TextBox1");
return (oTextBox.Text == "My Data");
}
}
You can use it like this from the page:
CMyDataClass oMyDataClass = new CMyDataClass();
if (oMyDataClass.CompareText(this)) {
Response.Write("Ok!");
}

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#";
}
}
}

Get POST data in C#/ASP.NET

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" />

Categories

Resources