How to link up ASP.Net page to code? - c#

I have a list:
<ul class="question">
<li>eBook Reader</li>
<li>Normal Mobile</li>
<li>Smartphone</li>
<li>PC / Laptop</li>
<li>Landline Telephone</li>
<li>Tablet</li>
<li>Games Console</li>
</ul>
Continue
A user is able to click any of the <li> items and it will add a class of selected to it. When they click continue, it needs to run at a method on the server which will take in the index of the <li> selected and do something with it.
The trouble is I've no idea how to do this with .aspx pages. I tried having this:
<asp:LinkButton runat="server" OnClick="ContinueClick" Text="Continue" CssClass="button next" />
Instead of the existing <a> tag but I can't seem to be able to pull anything meaningful out of it.

I think this should be a radio button list, and then take the selected value from there instead of using a list. Take a look at this link to see how to use a radio button list.
I think when you want a user to single select from a group, then a radio button list is the correct option. When you want a multi-select, then use a checkbox list.
The code will be similar to this...
<asp:RadioButtonList ID="questions" runat="server">
<asp:ListItem>eBook Reader</asp:ListItem>
<asp:ListItem>Normal Mobile</asp:ListItem>
<asp:ListItem>Smartphone</asp:ListItem>
<asp:ListItem>PC / Laptop</asp:ListItem>
<asp:ListItem>Landline Telephone</asp:ListItem>
<asp:ListItem>Tablet</asp:ListItem>
<asp:ListItem>Games Console</asp:ListItem>
</asp:RadioButtonList>
protected void ContinueClick(object sender, System.EventArgs e)
{
//questions.SelectedItem.ToString();
}

Add an Id and runat="server" on the elements that you would like to access on the server-side with their attributes and css-class.
You can also solve this by adding radio buttons, instead of a list.
Another solution to your issue might be a hidden control that holds the id of the selected element.

You can manually trigger postbacks to ASP.NET from JavaScript like this ASP.NET postback with JavaScript

Related

ASP.NET populate lists referencing each other on selected index change

I have an ASP.NET control with three listboxes: LBParent, LBChild1 and LBChild2.
LBParent has to be filled programmatically. I do this in Page_Load.
When the user selects a value in LBParent, I want to fill both LBChild1 and LBChild2 with some data, programmatically. The children lists must also keep track of their selected value.
Basically, the parent list is a list of users, the first list is a list of permissions the user has, the second list is a list of permissions the user doesn't have.
My plan is to add two buttons to move permissions between the two lists.
Unfortunately, I cannot get this to work properly.
If I populate the parent list in Page_Load, the selected index seems to reset. I used ViewState to save the index... but this seems to require an additional refresh, because it doesn't update after the PostBack. This is not acceptable.
If I populate the children listboxes on the OnParentSIC event, there is no way I can keep track of their selected index. The OnChildXSIC events never fire, because the listboxes get repopulated "too soon". (?)
How can I get this to work as intended? Maybe there is a better solution but I'd really like to understand how to get this solution to work, as I can't see a possible solution at the moment.
Control.ascx
<%# Control Language="C#" AutoEventWireup="true" EnableViewState="True" CodeBehind="..." Inherits="..." %>
<form runat="server">
<asp:ListBox ID="LBParent" runat="server" CssClass="form-control"
AutoPostBack="true" OnSelectedIndexChanged="OnParentSIC" />
<asp:ListBox ID="LBChild1" runat="server" CssClass="form-control"
AutoPostBack="true" OnSelectedIndexChanged="OnChild1SIC" />
<asp:ListBox ID="LBChild2" runat="server" CssClass="form-control"
AutoPostBack="true" OnSelectedIndexChanged="OnChild2SIC" />
</form>
Control.ascx.cs
protected void Page_Load(object sender, EventArgs e)
{
// Populate parent
for(...) LBParent.Items.Add(...);
}
The Onchange-event fires, but before that the OnLoad fires.
So:
The user clicks on an selection
A postback is triggered
At the server the Onload fires (and rebuilds the list)
The OnSelectedIndexChanged fires (which lost the selection by now)
So I would try to save the current-selected-index before you rebuild the list (in the Onload).
If you restore it later on while you are in the same 'postback' you can save it in a simple variable. No need to store in a Viewstate or Session.
use Like this
If You are on the Same Page then You can Use ViewState/Hidden Fields
to Maintain States
First Time Adding ListItem on PageLoad Use Like this
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
AddListItems();
}
}
Protected Void AddListItems()
{
// Populate parent
for(...) LBParent.Items.Add(...);
for(...) SecondList.Items.Add(...);
for(...) ThirdList.Items.Add(...);
}

Adding a ASP Control to page from Code Behind within InnerHTML

I'm trying to add a button to the webpage, from the code behind. I have a single empty div on my main page that visible on and off, when needed. However the content I wish to create dynamically as the div content can change dependent on conditions.
I have realised that within my ASP Control I use a / (backslash) which cancels out my HTML. The problem I now have is understanding how I can get around this with code, is there a way to add ASP Controls to the web page? I am open to suggestions outside of the InnerHtml.
I'm creating my Button like so (in my Code Behind):
string buttonout = string.Format("<asp:Button ID=\"helpButton_0\" CommandArgument=\"0\" CssClass=\"HelpButton\" runat=\"server\" Text=\"?\"/>");
innercontent[0] = string.Format("<table><tr><td>Lead Passenger Information</td></tr><tr><td>Here by deafaul we used your detaisl from your profile, if you're not the lead passenger (As in you're booking for someone else) then please change details.</td></tr><tr><td>{0}</td></tr></table>"+ buttonout);
As Said above, The reason this doesn't work is because of InnerHtml hating backslashes, I think.
I do have a solution to this; and that's by adding more divs to the page.
<div id="HelpBoxDiv" runat="server" Visible="false">
<div id="HelpBoxDiv_Top" runat="server" Visible="true">
</div>
<div id="HelpBoxDiv_Bottom" runat="server" Visible="true">
<asp:Button ID="button_HelpBox_false" runat="server" />
</div>
</div>
I would then add my Innerhtml to the _Top Div, instead of the HelpBoxDiv which I am currently doing now. However this solution doesn't teach me anything.
I am hesitant to ask questions here, as I know a lot of question have been asked and I am sure this one has before, but I didn't find a solution. Any help is much appreciated.
Thank you.
I have realised that within my ASP Control I use a / (backslash) which
cancels out my HTML. The problem I now have is understanding how I can
get around this with code, is there a way to add ASP Controls to the
web page? I am open to suggestions outside of the InnerHtml.
You cannot add ASP.Net server control like a literal string.
Instead, you want to add the dynamic server control to the following approach -
ASPX
<asp:PlaceHolder runat="server" ID="PlaceHolder1"></asp:PlaceHolder>
Code Behind
protected void Page_Init(object sender, EventArgs e)
{
var button = new Button
{
ID = "helpButton_0",
CommandArgument = "0",
CssClass = "HelpButton",
Text = "?"
};
button.Command += button_Command;
PlaceHolder1.Controls.Add(button);
}
private void button_Command(object sender, CommandEventArgs e)
{
// Handle dynamic button's command event.
}

DropDown values lost when FileUpload.IsInFileUploadPostBack

i'm working on a web project. I have a dropdown and i need the selectedvalue for uploading a file using asp:AjaxFileUpload.
Issue: when uploading a file, dropdown values are lost and the selectedvalue will be blank. I don't want to use a Session variable because if I open the same page in two tabs with different dropdown.selectedvalue, the other page might get the wrong session variable. Please help me find another way of getting the dropdown.selectedvalue when uploading a file,
your help will be really appreciated
Try this.
Enclose your DropDownList in an asp UpdatePanel as below:
<asp:UpdatePanel id="someid" runat="server>
<ContentTemplate>
<asp:DropDownList ID="yourdropdownlist" runat="server"></asp:DropDownList>
</ContentTemplate>
</UpdatePanel>
This is because your page is posting back each time.
Set AutoPostBack='false' and use Page.IsPostback property while populating and dealing with drop down box.
MSDN For IsPostBack:
http://msdn.microsoft.com/en-us/library/system.web.ui.page.ispostback.aspx
Hope Its Helpful.
You can use update panel and inside that put your dropdown, file upload control etc..
in your code behind on Page_Load check below condition and bind data.
if (!IsPostBack && !IsCallback && !AjaxFileUpload1.IsInFileUploadPostBack) // Need to prevent normal stuff on ajaxFileUpload PostBack
{
// bind drop down , gridview etc..
}

how to access repeater label value in javascript

This is my javascript
function btnEditClick() {
alert(document.getElementById('<%=LblRefPhyID.ClientID %>').value);
}
<asp:Repeater ID="repeaterRefPhysicianList" runat="server">
<ItemTemplate>
<tr onclick="selectRow(this);">
<td class="csstablelisttd" style="display: none;">
<asp:Label ID="LblRefPhyID" runat="server" Text='<%#Eval("Ref_Phy_ID")%>'></asp:Label>
</td>
on clientclick of Edit button i have to pass RefphyId to another page how can i do that..
It's a repeater. That means that the ItemTemplate will be repeated for each item in your databound collection.
This comes with a caveat: IDs are supposed to be unique. So when you say that your asp:Label has an ID of LblRefPhyID, ASP.NET automagically does you the favor of generating unique IDs for each instance of the repeater that eventually makes its way to your generated HTML. These generated IDs will be based on your original value of LblRefPhyID, but it won't be exactly that, so a plain document.getElementById() outside of the repeater won't work.
There are many ways to work around this, and the very first step you need to do is to actually write some code that will take the automatic generated IDs into account. Maybe write some Javascript to cache the IDs using LblRefPhyID.ClientID, maybe do it dynamically onclick, whatever.
EDIT
And, oh yeah, #Pointy is completely correct in stating that label elements don't have values, just their inner HTMLs. I don't get why he got downvoted for giving a correct response.
Try to set css class instead of id and bind elements click event by class name.
I'm using jquery for this:
$(document).ready(function(){
//bind click event on our label class
$('.lblRef').live('click', function(){
alert($(this).text());
});
});
And this in asp.net page code:
<asp:Label CssClass="lblRef" runat="server" Text='<%#Eval("Ref_Phy_ID")%>'></asp:Label>
HTML <label> elements don't have a "value". They do have contents:
alert(document.getElementById('<%=LblRefPhyID.ClientID %>').innerHTML);
Best way would be to check what is the pattern of id generated by the repeater on the client side and then you can use that id to get the value of the label using innerHTML.
For instance in your case id generated may be :
repeaterRefPhysicianList_LblRefPhyID_01 to till the number of rows in source.
So you can use this information with innerHTML to get the value of the label..
All in all just check your html page you will know what to do next :)

BulletedList onClick not firing

Ugh, this is driving me mad
Im trying to build up a dynamic menu from a bulletedList, most menu items are plain links however the log out button needs to perform some cleanup code.
I cant for the life of me get the BullettedLists onclick event to fire.
The BulletedList is inside a user control (if that makes a difference)
Any ideas?
Or - any ideas for an alternative, better solution?
Code below
BulletedList
<asp:BulletedList OnClick="menu_Click" runat="server" CssClass="MainMenu" ID="loggedInMenu" DisplayMode="HyperLink" />
Adding an element
loggedInMenu.Items.Add(new ListItem("Logout", ""));
Click handler
protected void menu_Click(object sender, BulletedListEventArgs e)
{
user.logout();
Response.Redirect("Default.aspx");
}
You're using the wrong DisplayMode for your BulletedList control. You should use a DisplayMode of LinkButton. When you use DisplayMode.HyperLink:
Users can click links to move to
another page. You must provide a
target URL as the Value property of
individual items.
This is from the MSDN docs for this control. (It's about 3/4 of the way down the page.)
When you use a BulletedList control in HyperLink mode, the value of your ListItem is the URL that you're navigating to. So your static page HTML controls would use ListItem.Value as the href attribute of the <a> tag.
Here's what the HTML markup looks like when you use a DisplayMode of HyperLink (it's a plain old HTML anchor tag w/ a href):
<li>One</li>
But since you want to postback, you should set the DisplayMode of your BulletedList control to LinkButton. When you do that, you'll enable a postback back to your page and your event handler will trap the event. You can then process the click appropriately then. The event argument that's passed in (of type BulletedListEventArgs) will have an Index property, and that will tell you what item in your list was clicked.
Here's the updated .aspx code that I used:
<asp:BulletedList ID="bullet" runat="server" DisplayMode="LinkButton"
onclick="bullet_Click">
<asp:ListItem Text="One" Value="1">One</asp:ListItem>
</asp:BulletedList>
Everything else is the same except the DisplayMode, which is set to LinkButton. When I use that, then my bullet_Click event handler is fired when I click a list item.
I hope this helps!!

Categories

Resources