How to pass a variable from .cs to .aspx - c#

As the title suggests, I want to add something to a table (inside aspx page) depending on some infos I get from a database (so if I have an item x in db I will make a bool type variable in cs).
My question is, is there any method to send that bool to aspx so I can use it inside an if statement (in order to add the respective columns to my table).

You don't need a session variable here, you can simply declare a class level property and use it in your ASPX page:-
public bool variable { get; set; }
and then directly use it in your aspx page:-
<%=variable %>

You can store the value of bool in session and display it in aspx, something like that
bool val;
// Your code
Session["value"] = val;
and use it in aspx such as
<%= Session["value"]%>

You can use a div and make your own HTML code in the .cs code behind file.
Or, you could simply use some labels and give information like that.
html:
<div>
<table>
<tr>
<td><asp:Label id="somelabel" runat="server" /></td>
</tr>
</table>
.cs
somelabel.Text = "yourdata";
Or you could add all your html code to a single string. Then, if your div is called divTable:
divTable.InnerHtml = liststring;
An example:
liststring = liststring +
"<img src=" + SQLdata.Tables[0].Rows[x]["imageSource"].ToString() +
"<ul style='list-style-type: none;'>" +
"<li>" + SQLdata.Tables[0].Rows[x]["Name"].ToString() + "</li>" +
"<li><b>Adress: </b>" + SQLdata.Tables[0].Rows[x]["Adress"].ToString() + "</li>" +
"<li><b>Website: </b><a href='http://" + SQLdata.Tables[0].Rows[x]["Website"].ToString() + "'>" + SQLdata.Tables[0].Rows[x]["Website"].ToString() + "</a></li>" + "</ul></div>";
divTable.InnerHtml = liststring;
Ofcourse you have to css a bit to get the correct display, but this will get you going I guess...

Related

Bind a List to a ListView

I am simply trying to create a list and add elements to it from the code behind. Each list element must be connected to a function in the code behind so I am using the Asp:LinkButton to do this. In the Default.aspx page I have:
<asp:ListView ID="ulNumTenants" runat="server">
<ItemTemplate>
<li>
<%# DataBinder.Eval(Container.DataItem, "XXX" ) %>
</li>
</ItemTemplate>
</asp:ListView>
And in the code behind I have the following:
var listItems = new List<LinkButton>();
int numberOfTenantsPossible = Space.MaxNumberOfTenants - (Space.MaleHousemates + Space.FemaleHousemates);
for (int itemCount = 0; itemCount < numberOfTenantsPossible; itemCount++ )
{
LinkButton currentItem = new LinkButton();
currentItem.CommandArgument = (itemCount + 1).ToString();
currentItem.CommandName = "Tenant_OnClick";
currentItem.Text = (itemCount + 1).ToString() + " tenants";
listItems.Add(currentItem);
}
ulNumTenants.DataSource = listItems;
ulNumTenants.DataBind();
The issue I am having is in the default.aspx code since I do not know what the expression field( "XXX" ) should be set to when I am not getting the entries from a database. Any suggestions are greatly appreciated.
Try this:
<%# Container.DataItem %>
I doubt it will work, since I think it will just take the string representation of a LinkButton instead of the HTML markup. However, why create the LinkButton dynamically in code? Try this instead:
Code Behind:
public class TenantViewModel
{
public string ID {get; set;}
public string Name {get; set;}
}
int numberOfTenantsPossible = Space.MaxNumberOfTenants - (Space.MaleHousemates + Space.FemaleHousemates);
var vms = new List<TenantViewModel>();
for (int itemCount = 0; itemCount < numberOfTenantsPossible; itemCount++ )
{
var vm = new TenantViewModel { ID = (itemCount + 1).ToString(), Name = (itemCount + 1).ToString() + " tenants"};
vms.Add(vm);
}
ulNumTenants.DataSource = vms;
ulNumTenants.DataBind();
ASPX:
<asp:ListView ID="ulNumTenants" runat="server">
<ItemTemplate>
<li>
<asp:LinkButton runat="server" CommandName="Tenant_OnClick" CommandArgument='<%# (Container.DataItem as TenantViewModel).ID' Text='<%# (Container.DataItem as TenantViewModel).Name' />
</li>
</ItemTemplate>
</asp:ListView>
That allows you to keep UI element declaration in your ASPX markup, and instead of creating all the buttons in your code behind, you just create a view model to bind it to. Container.DataItem will be an object, so we use the as syntax to convert it to the correct type TenantViewModel so we can access the properties. This results in much cleaner code. Instead of a ListView, you might also consider binding to a Repeater. ListViews are typically for two way binding directly to a database, but we're binding to a custom IEnumerable.
Also, if you do find that this markup is significantly cleaner, you might consider looking into ASP.NET MVC. The markup gets even cleaner there with Razor syntax, because you won't have to worry about casting to the correct type. Instead of using a repeater, you'd just use a foreach loop.

Assign HiddenField values programmatically in a loop

On default.aspx I have the following hidden fields:
<asp:HiddenField runat="server" ID="icon1" />
<asp:HiddenField runat="server" ID="icon2" />
<asp:HiddenField runat="server" ID="icon3" />
As you can see, the name of the field is the same each time but increments by 1 up to 3.
In my code behind I have been doing this (if statements and other code removed for brevity - this is the meat of it):
icon1.Value = "Bonus1";
icon2.Value = "Bonus2";
icon3.Value = "Bonus3";
Must I assign the iconX.Value individually every time like that? Can I do it all in one shot in a loop (also with everything else removed for brevity)?
for (int i = 1; i <=3; i++)
{
icon(i).Value = "Bonus" + i.ToString();
}
Everything I have read leads me to believe this is not possible in C#. Let's pretend I have 50 iconX.Value = whatever to assign. A loop makes the most logical sense. Possible?
A loop makes the most logical sense. Possible?
Yes. Use the FindControl method of the page to look up a control by its ID:
for (int i = 1; i <= 3; i++)
{
HiddenField field = (HiddenField)this.FindControl("icon" + i);
field.Value = "Bonus" + i.ToString();
}
Note: Because the return type of FindControl is Control, you must cast the result in order to access properties specific to HiddenField.
You have to create a asp:panel in the HTML section.
Then, in the c# code, make a loop and create elements like you describe.
When the element is fully configured, add it to the panel.
.ASPX file
<asp:Panel ID="panel_controls" runat="server"> </asp:Panel>
C# code
for (int i = 1; i <= 3; i++) {
HiddenField myField = new HiddenField();
myField.ID = "icon" + i;
myField.Value = "Bonus" + i;
panel_controls.Controls.Add(myField);
}

Easiest way to append a string with different values by checking if hiddenfields are empty

I'm building an audit trail in C#, asp.net. On the .aspx page I have several hidden fields which associate themselves with regular fields (i.e. txtFirstName -> firstNameTrackerHiddenField). I have it set up so that when the user inputs/selects data to a field, the hidden field gets a value set to it. Example:
protected void txtFirstName_TextChanged(object sender, EventArgs e)
{
this.FirstNameTrackerHiddenField.Value = "1";
}
Now to build my Audit Log I was thinking of just checking through each hidden field, pulling the ones that aren't null, and appending a string, depending on which field the user has inputed/changed. I could do a bunch of nested if statements but that would be really sloppy.
Sorry if I'm not making any sense, I'm still a little new to the coding world and I thought this methodology would be pretty neat and easy to implement. Here's what I have so far in the auditLog method:
protected string auditLogString()
{
string auditLog = this.txtAuditLogReadOnly.Text + System.Environment.NewLine + System.Environment.NewLine +
DateTime.Now.ToString() + "- (Incident saved by: " + Page.User.Identity.Name + ") ";
if (this.FirstNameTrackerHiddenField.Value != string.Empty)
{
auditLog += "- with changes to First Name."
if (this.LastNameTrackerHiddenField.Value != string.Empty)
{
auditLog += "- with changes to Last Name."
}
}
return auditLog;
}
And the list goes on. There's about 50 fields to cycle through, so that's why I was wondering if there was a better way to go about this... Thanks for any input, and please don't be rough with me... :)
A cleaner way to if/else-ing every HiddenField would be to loop through the controls on your page, check their type and if they're a HiddenField with a value, do something with the value.
foreach (Control ctrl in this.Controls)
{
if (ctrl is HiddenField)
{
if (!string.IsNullOrEmpty((ctrl as HiddenField).Value))
{
// do something
}
}
}
Ok, so a few things here. First - try not to do string concatenation using + in C#, unless you're concatenating constant expressions (which DateTime.Now and Page.User.Identity.Name are not). Use a StringBuilder instead. Strings in C# are immutable.
Second, you can just add a custom attribute to your textboxes and collect their value server-side; there's no need for additional hidden fields.
So, given an example form like: -
<asp:TextBox ID="txtAuditLogReadOnly" runat="server" />
<div id="divContainer" runat="server">
<asp:TextBox ID="t1" runat="server" fieldname="First Name" />
<asp:TextBox ID="t2" runat="server" fieldname="Last Name" />
<asp:TextBox ID="t3" runat="server" fieldname="Shoe Size" />
<asp:TextBox ID="t4" runat="server" fieldname="Banana" />
</div>
(Note 'fieldname' attribute)
You could scrape the values into your audit log like so: -
var builder = new StringBuilder(
string.Format("{0}{1}{2:dd/MM/yyyy hh:mm}- (Incident saved by: {3})",
txtAuditLogReadOnly.Text,
Environment.NewLine,
DateTime.Now,
Page.User.Identity.Name));
var controls = from Control c in divContainer.Controls
select c;
foreach (var ctl in controls)
{
if (ctl is TextBox)
{
var txt = (TextBox)ctl;
if (!string.IsNullOrEmpty(txt.Text))
{
string fieldname = txt.Attributes["fieldname"];
builder.AppendFormat(" - with changes to {0}", fieldname);
}
}
}
return builder.ToString();

jquery append question

In my ASP.net project, I am using a jquery script to update the id=person field in the URL bar:
$("form").append("<input type='hidden' name='hiddenEmployeeId' value='" + $('#EmployeeSelected').val() + "' />");
This is triggered when the value of the drop-down box changes. It works great, except for the fact that when you change it...it just appends the new id behind the first id, which is exactly what it's supposed to be doing.
However, I only want one id, obviously. What can I do here to accomplish this? Is there a way to CLEAR that first, and then append it?
Thanks!
Check to see if it exists, if so, set the value. If it doesn't append it:
var input = $('input[name=hiddenEmployeeId]');
if(input [0]) {
input.val($('#EmployeeSelected').val());
} else {
$("form").append("<input type='hidden' name='hiddenEmployeeId' value='" + $('#EmployeeSelected').val() + "' />");
}
Cant you just change the value on the input named 'hiddenEmployeeId' or does it not exists the first time?
$("input[name=hiddenEmployeeId]").val($('#EmployeeSelected').val());
you can do something like this:
$($('input[name=hiddenEmployeeId]')[0] || $('<input type="hidden" name="hiddenEmployeeId">').appendTo("form.selector")[0]).val($('#EmployeeSelected').val());
and change the "form.selector" to the form you are working with.

ASP.NET - Getting the object inside Repeater ItemTemplate with/without Eval

I am new to Repeater and DataBinding and I need help using it.
In PageLoad, I have
var photos = from p in MyDataContext.Photos
select new {
p,
Url = p.GetImageUrl()
};
repeater1.DataSource = photos;
repeater1.DataBind();
In the Repeater control, I have
<ItemTemplate>
<% Photo p = (Photo) Eval("p"); %> <!-- Apparently I can't do this -->
...
<asp:TextBox runat="server" ID="txtTime" Text='<%= p.Time == null ? "" : ((DateTime)p.Time).ToString("dd/MM/yyyy HH:mm:ss") %>' />
...
</ItemTemplate>
But that is wrong.
What I need is to get the Photo object in ItemTemplate so I can do things with it (eg. to display the time as in the second line in ItemTemplate above). Is it even possible to do this in a Repeater?
Could someone point me to the right direction?
Thank you in advance!
Try something like this In the onDatabound event
if (e.Item.ItemType = ListItemType.Item)
{
photo p = (photo)e.DataItem;
Textbox txtTime = (Textbox)e.Item.FindControl("txtTime");
txtTime.text = (p.Time == null ? "" : ((DateTime)p.Time).ToString("dd/MM/yyyy HH:mm:ss"));
}
Edit -
Sorry, I didn't see the extra Url there. I looks like you might have to create a small class or struct.
See this Stackoverflow link for a hack workaround.
Paul Suart's post in that thread made a valid point.
Have you tried just:
<%# Eval("p") %>
instead of
<% Photo p = (Photo) Eval("p"); %>
I use an alternative method. In my "Register" I import the object class:
<%# Import Namespace="Test.Test.TO" %>
With this It's possible use your object...
Next, I created an object the same type I want to bound in my codebehind, global variable...
public Test test;
In my Repeater inside ItemTemplete:
<span style="display: none;"> <%# test = (Test)Container.DataItem %> </span>
Now, you can use all object's properties, inclusive ToString to format with culture...
Sorry for my english.

Categories

Resources