I have an ASP.NET application that uses jQuery. My ASP.NET application dynamically generates some HyperLink elements based on some values in a database. When a user clicks one of these HyperLink elements, I want to display a jQuery dialog box that allows the user to edit the text of the HyperLink. I have this part working.
When a user clicks the "Save" button, I need to read the values of the HyperLink elements and save them back to the database. Currently, I get the initial values of the HyperLink elements. However, I cannot get any modified values. How do I get the values that were provided by the user? I have provided my .aspx and .aspx.cs code here:
test
Report:
<div id="recommendDialog" title="Number">
<table border="0" cellpadding="0" cellspacing="0">
<tr><td>Number</td></tr>
<tr><td><input id="optionName" type="text" /></td></tr>
</table>
</div>
<asp:Button ID="saveButton" runat="server" Text="Save" OnClick="saveButton_Click" />
</div>
</form>
<script type="text/javascript">
var editingID = null;
$("#recommendDialog").dialog({
autoOpen: false,
height: 200,
modal: true,
buttons: {
Cancel: function() {
$(this).dialog('close');
},
'OK': function() {
var newValue = $("#optionName").val();
if (editingID != null) {
$(editingID).attr("name", newValue);
$(editingID).html(newValue);
}
$(this).dialog('close');
}
},
close: function() {
}
});
function update_Click(link) {
editingID = "#" + link.id;
$("#optionName").val(link.name);
$('#recommendDialog').dialog('open');
}
</script>
Here is my code-behind:
public partial class _Default : System.Web.UI.Page
{
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
AddHyperlinks();
}
protected void Page_Load(object sender, EventArgs e)
{}
protected void saveButton_Click(object sender, EventArgs e)
{
foreach (TableCell cell in reportTable.Rows[0].Cells)
{
HyperLink h = (HyperLink)(cell.Controls[0]);
string newValue = h.Attributes["name"];
// Save value to database here. newValue does not show
// changed values.
Console.WriteLine(newValue);
}
}
private void AddHyperlinks()
{
TableRow row = new TableRow();
for (int i = 1; i < 11; i++)
{
HyperLink hyperlink = new HyperLink();
hyperlink.NavigateUrl = "#";
hyperlink.Text = i.ToString();
hyperlink.Attributes.Add("id", "h" + i);
hyperlink.Attributes.Add("name", i.ToString());
hyperlink.Attributes.Add("onclick", "update_Click(this);");
AddLinkButtonToRow(hyperlink, row);
}
reportTable.Rows.Add(row);
}
private void AddLinkButtonToRow(HyperLink linkButton, TableRow row)
{
TableCell cell = new TableCell();
cell.Controls.Add(linkButton);
row.Cells.Add(cell);
}
}
What you're trying to do isn't possible that way. You create links every time the page is created. Although you change the name of these links in JavaScript, these values are not posted back to you.
On Sumbit, only form elements get posted back to the server (<input>s, for example), not <a> elements, so your server doesn't "know" the changes were made.
Secondly, even if you'll change the <a>s to <input>s, you still have a problem: you won't be able to find these values in reportTable.Rows[0].Cells as you expect. Normally asp.net will fill these values correctly, even for dynamically generated controls, but not here - since you've changed their names! Asp.net cannot rebind these values.
So, what should you do? One option is to add an hidden field to every cell.
On AddLinkButtonToRow, add the following:
HtmlInputHidden hidden = new HtmlInputHidden();
hidden.ID = "hidden" + linkButton.ID;
hidden.Name = hidden.ID; //so it will be posted!
hidden.Style["display"] = "none"; //better to have a CssClass
Using jQuery, which you seem to know, change the values of these input fields, not their names (something like $(editingID).parent().find(":hidden")).
Next, you might not see the values on the controls, but you can find them at Request.Form["hiddenh1"] ... Request.Form["hiddenh11"] - All input fields will names will be posted, and you know their names this time.
I'm not sure where or what "ReportTable" and it's tablecells are, but I'm guessing your problem is that you're manipulating the value of some tags on the client using jQuery, and expecting them to be posted back to the server?
This won't work. The page got rendered with known values of your HyperLink controls in ViewState. Since tags are not input types, they will not post a value back to the server on a postback, and ViewState will always re-initialize them with their original values. Any manipulation must be done on the server side.
I would recommend doing what ScottE suggests and do your update with jquery ajax.
Related
I am attempting to create a calendar which is just a simple UI to display dates and dates to users of our system. I have overridden the Calendar's "DayRender" event to gain access to each cell and then insert a couple of dynamic controls to display specific data. The display of the controls works great. However, I recently wanted to add a LinkButton with command arguments and capture the event to run some other logic and change the UI. I have gotten the LinkButton to display properly and it renders as a simple "" tag with the ID that is assigned. However clicking on the link does nothing and it appears that the normal "href='...javascript action...'" portion of the link is not being generated. I have a feeling this is all due to the fact that I am adding the control at the Day Render stage in the page life cycle. But if that was the case the control probably would not show up at all.
Any ideas as to why the click action is not being added yet the text and everything else are? Code is below.
Thanks for your time
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
if (Schedule != null)
{
var dayReq = from day in Schedule
where day.RequiredDate == e.Day.Date
where day.RequiredQty != 0
select day;
if (dayReq.FirstOrDefault() != null)
{
//Open the Date
e.Cell.Controls.Add(new LiteralControl("<br /><div class=\"auth-sched-req\">Req Qty: <strong>" + String.Format("{0:#,#.###}", dayReq.FirstOrDefault().RequiredQty) + "</strong><br />Prom Date: "));
//Create a link button for the promise date
LinkButton lb = new LinkButton();
lb.ID = dayReq.FirstOrDefault().ItemId.ToString();
lb.Text = dayReq.FirstOrDefault().RequiredDate.ToShortDateString();
lb.CommandName = "ShowPromise";
lb.CommandArgument = dayReq.FirstOrDefault().ItemId.ToString();
lb.Command +=new CommandEventHandler(lb_Command);
e.Cell.Controls.Add(lb);
//Close the Date
e.Cell.Controls.Add(new LiteralControl("</div>"));
}
}
}
protected void lb_Command(Object sender, CommandEventArgs e)
{
//Do some magic here
Response.Write(e.CommandArgument.ToString());
}
try this
<script type="text/javascript">
function calendarClick(day) {
document.getElementById('<%= hfValue.ClientID %>').value = day;
document.getElementById('<%= ghostButton.ClientID %>').click();
}
</script>
<asp:Button ID="ghostButton" runat="server" Style="display: none" OnClick="ghostButton_Click" />
<asp:HiddenField ID="hfValue" runat="server" />
code behind:
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
// ...
e.Cell.Attributes["onclick"] = string.Format("calendarClick({0})", dayReq.FirstOrDefault().ItemId.ToString());
// ...
}
protected void ghostButton_Click(object sender, EventArgs e1)
{
string value = hfValue.Value;
// ...
}
Check if AutoEventWireup is set to true i.e.
AutoEventWireup="true"
I ended up going another route with this request. None of the proposed solutions worked and I never could get it to work. One option we looked at was creating a custom table to build the control. We ended up changing where the information was changed and just used the calendar control as the display mechanism.
Sorry for the delay!
I am familiar with creating and persisting dynamic controls on the first load of a page and on subsequent postbacks but I am having trouble with the following user initiated scenario...
In my demo I have a placeholder, two buttons and a literal
<div>
<asp:PlaceHolder ID="phResponses" runat="server" />
</div>
<div>
<asp:Button ID="btnAdd" Text="Add" runat="server" OnClick="Add"/>
<asp:Button ID="btnInspect" Text="Inspect" runat="server" OnClick="Inspect"/>
</div>
<div>
<asp:Literal ID="litResult" runat="server"/>
</div>
I want the user to be able to click the add button to provide a response so I have...
protected void Page_Init(object sender, EventArgs e)
{
BuildControls();
}
protected void Add(object sender, EventArgs e)
{
BuildControls();
}
protected void BuildControls()
{
phResponses.Controls.Add(new LiteralControl { ID = "response_" + _Count.ToString() });
_Count++;
}
_Count is a static member variable to enable me to have unique ids for the new controls. I realise I need to rebuild the dynamic controls on Page_Init but the problem is that I end up with 2 new Literal controls on every postback. Also if any Text property is put into the new controls it is lost when the controls are rebuilt.
So how do I avoid adding multiple controls and how do I persist newly added properties when rebuilding these controls?
I use the following to inspect the responses
protected void Inspect(object sender, EventArgs e)
{
foreach (var control in phResponses.Controls)
{
if (control is LiteralControl)
{
litResults.Text += "<p>" + control.Text + " : " + control.ID + "</p>";
}
}
}
Which itself adds another unwanted control because of the rebuilding on Page_Init
I'd not sure that I quite understand what you're asking, but it looks like you just want to ensure that BuildControls is only called once per lifecycle. You could do that by making the following changes:
Add a new private bool _isControlsBuilt = false;.
Change Page_Init to check _isControlsBuilt before calling BuildControls.
Set _isControlsBuilt to true within BuildControls.
Make sure that BuildControls occurs earlier in the page lifecycle than Page_Init.
As for losing the values of controls on postback, it'll be that they're never hitting the viewstate. I'm not sure if it'd work, but my first guess would be to add a line to the end of BuildControls to call Page.RegisterRequiresControlState:
protected void BuildControls()
{
LiteralControl newLiteral = new LiteralControl { ID = "response_" + _Count };
this.RegisterRequiresControlState(newLiteral);
phResponses.Controls.Add(newLiteral);
_Count++;
_isControlsBuilt = true;
}
If that doesn't work (which might imply that it's the _view_state, not the _control_state that matters to you here), you may need to look at rolling your own viewstate. I wrote about how to do that in my answer to #3854193, which you might find useful.
I am currently facing a problem. How to get the latest selected value from a asp.net checkbox list?
From looping through the Items of a checkbox list, I can get the highest selected index and its value, but it is not expected that the user will select the checkbox sequentially from lower to higher index. So, how to handle that?
Is there any event capturing system that will help me to identify the exact list item which generates the event?
If I understood it right, this is the code I'd use:
protected void CheckBoxList1_SelectedIndexChanged(object sender, EventArgs e)
{
int lastSelectedIndex = 0;
string lastSelectedValue = string.Empty;
foreach (ListItem listitem in CheckBoxList1.Items)
{
if (listitem.Selected)
{
int thisIndex = CheckBoxList1.Items.IndexOf(listitem);
if (lastSelectedIndex < thisIndex)
{
lastSelectedIndex = thisIndex;
lastSelectedValue = listitem.Value;
}
}
}
}
Is there any event capturing system that will help me to identify the exact list item which generates the event?
You use the event CheckBoxList1_SelectedIndexChanged of the CheckBoxList. When a CheckBox of the list is clicked this event is called and then you can check whatever condition you want.
Edit:
The following code allows you to get the last checkbox index that the user selected. With this data you can get the last selected value by the user.
protected void CheckBoxList1_SelectedIndexChanged(object sender, EventArgs e)
{
string value = string.Empty;
string result = Request.Form["__EVENTTARGET"];
string[] checkedBox = result.Split('$'); ;
int index = int.Parse(checkedBox[checkedBox.Length - 1]);
if (CheckBoxList1.Items[index].Selected)
{
value = CheckBoxList1.Items[index].Value;
}
else
{
}
}
Below is the code which gives you the Latest selected CheckBoxList Item.
string result = Request.Form["__EVENTTARGET"];
string [] checkedBox = result.Split('$'); ;
int index = int.Parse(checkedBox[checkedBox.Length - 1]);
if (cbYears.Items[index].Selected)
{
//your logic
}
else
{
//your logic
}
Hope this helps.
Don't know about you, but as a user i wouldn't want the page to post back every time a checkbox item was checked.
This is the solution i would go with (jQuery):
Declare a server-side hidden field on your form:
<asp:HiddenField ID="HiddenField1" runat="server" EnableViewState="true" />
Then wire up client-side event handlers for the checkboxes to store checkbox clicked:
$('.someclassforyourcheckboxes').click(function() {
$('#HiddenField1').val($(this).attr('id'));
This is a lightweight mechanism for storing the ID of the "latest" checkbox clicked. And you won't have to set autopostback=true for the checkboxes and do an unecessary postback.
You dont HAVE to use jQuery - you can use regular Javascript, but, why do more work? =)
Then when you actually do the postback (on a submit button click i assume), just check the value of the hidden field.
Unless of course you WANT to postback on every checkbox click, but i can't envision a scenario in which you'd want this (maybe you're using UpdatePanel).
EDIT
The HTML of a checkbox list looks like this:
<input type="checkbox" name="vehicle" value="Bike" /> I have a bike
So, you can access three things:
Vehicle = $(this).attr('name');
Bike = $(this).attr('value');
I have a bike = $(this).html();
If you're trying to access the databound value, try the second technique.
Give that a try.
I have a page with a table of stuff and I need to allow the user to select rows to process. I've figured out how to add a column of check boxes to the table but I can't seem to figure out how to test if they are checked when the form is submitted. If they were static elements, I'd be able to just check do this.theCheckBox but they are programaticly generated.
Also I'm not very happy with how I'm attaching my data to them (by stuffing it in there ID property).
I'm not sure if it's relevant but I'm looking at a bit of a catch-22 as I need to known which of the checkboxes that were created last time around were checked before I can re-run the code that created them.
Edit:
I've found an almost solution. By setting the AutoPostBack property and the CheckedChanged event:
checkbox.AutoPostBack = false;
checkbox.CheckedChanged += new EventHandler(checkbox_CheckedChanged);
I can get code to be called on a post back for any check box that has changed. However this has two problems:
The call back is processed after (or during, I'm not sure) Page_Load where I need to use this information
The call back is not called for check boxes that were checked when the page loaded and still are.
Edit 2:
What I ended up doing was tagging all my ID's with a know prefix and stuffing this at the top of Form_Load:
foreach (string v in this.Request.Form.AllKeys)
{
if (v.StartsWith(Prefix))
{
var data = v.Substring(Prefix.Length);
}
}
everything else seems to run to late.
I'm going to assume you're using a DataList but this should work with and Control that can be templated. I'm also going to assume you're using DataBinding.
Code Front:
<asp:DataList ID="List" OnItemDataBound="List_ItemDataBound" runat="server">
<ItemTemplate>
<asp:CheckBox ID="DeleteMe" runat="server"/>
<a href="<%# DataBinder.Eval(Container, "DataItem.Url")%>" target="_blank">
<%# DataBinder.Eval(Container, "DataItem.Title")%></a>
</ItemTemplate>
</asp:DataList>
<asp:Button ID="DeleteListItem" runat="server" OnClick="DeleteListItem_Click" ></asp:Button>
Code Behind:
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadList();
}
protected void DeleteListItem_Click(object sender, EventArgs e)
{
foreach (DataListItem li in List.Items)
{
CheckBox delMe = (CheckBox)li.FindControl("DeleteMe");
if (delMe != null && delMe.Checked)
//Do Something
}
}
LoadList();
}
protected void LoadList()
{
DataTable dt = //Something...
List.DataSource = dt;
List.DataBind();
}
protected void List_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
{
string id = DataBinder.Eval(e.Item.DataItem, "ID").ToString();
CheckBox delMe = (CheckBox)e.Item.FindControl("DeleteMe");
if (delMe != null)
delMe.Attributes.Add("value", id);
}
}
}
First, make sure that each Checkbox has an ID and that it's got the 'runat="server"' in the tag.
then use the FindControl() function to find it.
For example, if you're looping through all rows in a GridView..
foreach(GridViewRow r in Gridview1.Rows)
{
object cb = r.FindControl("MyCheckBoxId");
if(r != null)
{
CheckBox chk = (CheckBox)cb;
bool IsChecked = chk.Checked;
}
}
Postback data is restored between the InitComplete event and the PreLoad event. If your checkboxes are not created until later then the checkboxes will play "catch up" with their events and the data will be loaded into the control shortly after it is created.
If this is to late for you then you will have to do something like what you are already doing. That is you will have to access the post data before it is given to the control.
If you can save the UniqueId of each CheckBox that you create then can directly access the post data without having to given them a special prefix. You could do this by creating a list of strings which you save the ids in as you generate them and then saving them in the view state. Of course that requires the view state to be enabled and takes up more space in the viewstate.
foreach (string uniqueId in UniqueIds)
{
bool data = Convert.ToBoolean(Request.Form[uniqueId]);
//...
}
Your post is a little vague. It would help to see how you're adding controls to the table. Is it an ASP:Table or a regular HTML table (presumably with a runat="server" attribute since you've successfully added items to it)?
If you intend to let the user make a bunch of selections, then hit a "Submit" button, whereupon you'll process each row based on which row is checked, then you should not be handling the CheckChanged event. Otherwise, as you've noticed, you'll be causing a postback each time and it won't process any of the other checkboxes. So when you create the CheckBox do not set the eventhandler so it doesn't cause a postback.
In your submit button's eventhandler you would loop through each table row, cell, then determine whether the cell's children control contained a checkbox.
I would suggest not using a table. From what you're describing perhaps a GridView or DataList is a better option.
EDIT: here's a simple example to demonstrate. You should be able to get this working in a new project to test out.
Markup
<form id="form1" runat="server">
<div>
<table id="tbl" runat="server"></table>
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
onclick="btnSubmit_Click" />
</div>
</form>
Code-behind
protected void Page_Load(object sender, EventArgs e)
{
for (int i = 0; i < 10; i++)
{
var row = new HtmlTableRow();
var cell = new HtmlTableCell();
cell.InnerText = "Row: " + i.ToString();
row.Cells.Add(cell);
cell = new HtmlTableCell();
CheckBox chk = new CheckBox() { ID = "chk" + i.ToString() };
cell.Controls.Add(chk);
row.Cells.Add(cell);
tbl.Rows.Add(row);
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
foreach (HtmlTableRow row in tbl.Rows)
{
foreach (HtmlTableCell cell in row.Cells)
{
foreach (Control c in cell.Controls)
{
if (c is CheckBox)
{
// do your processing here
CheckBox chk = c as CheckBox;
if (chk.Checked)
{
Response.Write(chk.ID + " was checked <br />");
}
}
}
}
}
}
What about using the CheckBoxList control? I have no Visual Studio open now, but as far as I remember it is a DataBound control, providing DataSource and DataBind() where you can provide a list at runtime. When the page does a postback you can traverse the list by calling something like myCheckBoxList.Items and check whether the current item is selected by calling ListItem.Selected method. This should work.
Add them in an override of the CreateChildControls method of the Page. Be sure to give them an ID! This way they get added to the control tree at the correct time.
IMHO The best way would be to use DataBound Templated Control though, i.e. something like a ListView (in .NET 3.5). then in pageload after postback traverse all items in the databound control and use item.FindControl to get at the actual checkbox.
What I ended up doing was tagging all my ID's with a know prefix and stuffing this at the top of Form_Load:
foreach (string v in this.Request.Form.AllKeys)
{
if (v.StartsWith(Prefix))
{
var data = v.Substring(Prefix.Length);
}
}
everything else seems to run to late.
I got a templated control (a repeater) listing some text and other markup. Each item has a radiobutton associated with it, making it possible for the user to select ONE of the items created by the repeater.
The repeater writes the radiobutton setting its id and name generated with the default ASP.NET naming convention making each radiobutton a full 'group'. This means all radiobuttons are independent on each other, which again unfortunately means I can select all radiobuttons at the same time. The radiobutton has the clever attribute 'groupname' used to set a common name, so they get grouped together and thus should be dependant (so I can only select one at a time). The problem is - this doesn't work - the repeater makes sure the id and thus the name (which controls the grouping) are different.
Since I use a repeater (could have been a listview or any other templated databound control) I can't use the RadioButtonList. So where does that leave me?
I know I've had this problem before and solved it. I know almost every ASP.NET programmer must have had it too, so why can't I google and find a solid solution to the problem? I came across solutions to enforce the grouping by JavaScript (ugly!) or even to handle the radiobuttons as non-server controls, forcing me to do a Request.Form[name] to read the status. I also tried experimenting with overriding the name attribute on the PreRender event - unfortunately the owning page and masterpage again overrides this name to reflect the full id/name, so I end up with the same wrong result.
If you have no better solution than what I posted, you are still very welcome to post your thoughts - at least I'll know that my friend 'jack' is right about how messed up ASP.NET is sometimes ;)
ASP.NET Tip: Using RadioButton Controls in a Repeater
This is the code for the JavaScript function:
function SetUniqueRadioButton(nameregex, current)
{
re = new RegExp(nameregex);
for(i = 0; i < document.forms[0].elements.length; i++)
{
elm = document.forms[0].elements[i]
if (elm.type == 'radio')
{
if (re.test(elm.name))
{
elm.checked = false;
}
}
}
current.checked = true;
}
The code is linked to the Repeater through the ItemDataBound event. For it to work properly, you need to know the name of the Repeater control, as well as the GroupName you're assigning to the RadioButtons. In this case, I'm using rptPortfolios as the name of the Repeater, and Portfolios as the group name:
protected void rptPortfolios_ItemDataBound(object sender,
RepeaterItemEventArgs e)
{
if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType
!= ListItemType.AlternatingItem)
return;
RadioButton rdo = (RadioButton)e.Item.FindControl("rdoSelected");
string script =
"SetUniqueRadioButton('rptPortfolios.*Portfolios',this)";
rdo.Attributes.Add("onclick", script);
}
REF: http://www.codeguru.com/csharp/csharp/cs_controls/custom/article.php/c12371/
Google-fu: asp.net radiobutton repeater problem
Indeed an unfortunate consequence of the id mangling. My take would be creating a - or picking one of the many available - custom control that adds support for same name on the client.
Vladimir Smirnov has already created a great custom control that resolves this issue. We have been using the GroupRadioButton in our projects and it has been working perfectly with radio buttons created inside of a repeater and others outside the repeater all being a part of the same group.
I use jQuery script:
<script type="text/javascript">
function norm_radio_name() {
$("[type=radio]").each(function (i) {
var name = $(this).attr("name");
var splitted = name.split("$");
$(this).attr("name", splitted[splitted.length - 1]);
});
};
$(document).ready(function () {
norm_radio_name();
});
// for UpdatePannel
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function () {
norm_radio_name();
});
</script>
I know this is an old post, but here's what I ended up doing with a listview. My listview is bound in VB codebehind, so I'm not sure if this will work well with a repeater, but I imagine it could be similar.
What I did was handle the OnCheckChanged event of the radiobuttons with a function that unselected any other radio buttons. Then I looked for the selected radio button when I navigated away from the page.
This solution avoids JavaScript and jQuery, and ignores the GroupName issue completely. It's not ideal, but it functions as (I) expected. I hope it's helpful for others.
Markup:
<asp:ListView ID="lvw" runat="server">
<LayoutTemplate>`
<table>
<th>Radio</th>
<tr id="itemPlaceholder"></tr>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr>
<td><asp:RadioButton ID="rdbSelect" runat="server" AutoPostBack="true"
OnCheckedChanged="rdbSelect_Changed"/></td>
</tr>
</ItemTemplate>
</asp:ListView>
Code:
Protected Sub rdbSelect_Changed(ByVal sender As Object, ByVal e As System.EventArgs)
Dim rb1 As RadioButton = CType(sender, RadioButton)
For Each row As ListViewItem In lvw.Items
Dim rb As RadioButton = row.FindControl("rdbSelect")
If rb IsNot Nothing AndAlso rb.Checked Then
rb.Checked = False
End If
Next
rb1.Checked = True
End Sub
And then when the Submit button is clicked:
Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
For Each row As ListViewItem In lvw.Items
Dim rb As RadioButton = row.FindControl("rdbSelect")
Dim lbl As Label
If rb IsNot Nothing AndAlso rb.Checked = True Then
lbl = row.FindControl("StudentID")
Session("StudentID") = lbl.Text
End If
Next
Response.Redirect("~/TransferStudent.aspx")
End Sub
This might be a little better..
I have a usercontrol which is essentially a set of radiobuttons inside a repeater, each instance of the usercontrol has a public property called FilterTitle, which is unique per instance.
add these two properties to your radiobutton replacing FilterTitle with your own public property name
onclick='<%# "$(\"input[name$=btngroup_" + FilterTitle + "]\").removeAttr(\"checked\"); $(this).attr(\"checked\",\"checked\");" %>' GroupName='<%# "btngroup_" + FilterTitle %>'
more simply..
onclick="$('input[name$=btngroup1]').removeAttr('checked'); $(this).attr('checked','checked');" GroupName="btngroup1"
Here's a pure Javascript solution for the sake of completeness.
Just add this onclick attribute to your RadioButton element(replace GroupName with your RadioButton's GroupName):
<asp:RadioButton ... GroupName="GroupName" onclick="SelectRadioButton('GroupName$',this)" ... />
And include this Javascript in your page:
<script type="text/javascript">
function SelectRadioButton(regexPattern, selectedRadioButton)
{
regex = new RegExp(regexPattern);
for (i = 0; i < document.forms[0].elements.length; i++)
{
element = document.forms[0].elements[i];
if (element.type == 'radio' && regex.test(element.name))
{
element.checked = false;
}
}
selectedRadioButton.checked = true;
}
</script>
Create a Custom Control and override UniqueID to the listview UniqueID + GroupName
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace MYCONTROLS
{
[ToolboxData("<{0}:MYRADIOBUTTON runat=server></{0}:MYRADIOBUTTON >")]
public class MYRADIOBUTTON : RadioButton
{
public override string UniqueID
{
get
{
string uid = base.UniqueID;
//Fix groupname in lisview
if (this.Parent is ListViewDataItem && GroupName != "")
{
uid = this.Parent.UniqueID;
uid = uid.Remove(uid.LastIndexOf('$'));
uid += "$" + GroupName;
}
return uid;
}
}
}
}
It’s a custom control that inherits from RadioButton (public class MYRADIOBUTTON : RadioButton).
If you do nothing in the class you get a normal RadioButton. Overriding the UniqueId you can change the logic for how the name attribute is rendered.
To still keep the name unique to other controls on the page (outside the listview) you can get the UniqueId from the ListView and add GroupName to that and add it to the RadioButton.
This fix the problem with Grouping RadioButtons on different rows in a listview. You may want to add some more logic with a property to turn this feature on/off so it behaves like a normal RadioButton.
I know this question is bit old, but I think it might help somebody, therefore posting my solution to this issue.
This issue has 2 parts:
To prevent selection of more than one radio button at a time.
To know which radio button was clicked in server-side code.
I had the similar issue with Radio button in Repeater. I found partial solution here:
Simple fix for Radio Button controls in an ASP.NET Repeater using jQuery
Please read the above article to get the understanding of the issue. I referred this article and it was good help. As mentioned above this issue has two parts, first is to prevent selection of more than one radio button at a time. Second, to know which radio button was clicked in server-side code. The solution posted in above article worked for me only for the first part. However code written there as well as updates to solution posted there did not work for me. So I had to modify it a bit to get it working. Here is my solution.
I wanted to create poll with Vote button. Name of my radio button (ID) is PollGroupValue with Groupname set to PollGroup in a repeater. Remember Groupname attribute in ASP.net is rendered as name attribute in generated html. My code is as follows:
<script type="text/javascript">
/* Step-01: */
$(document).ready(function () {
/* Step-02: */
$("[name*='PollGroup']").each(function () {
$(this).attr('ci-name', $(this).attr('name'));
});
/* Step-03: */
$("[name*='PollGroup']").attr("name", $("[name*='PollGroup']").attr("name"));
$('#Poll1_BtnVote').click(function (e) {
/* Step - 04: */
if ($("[name*='PollGroup']").filter(':checked').length == 0) {
alert('Please select an option.');
e.preventDefault();
}
/* Step - 05: */
$("[name*='PollGroup']").each(function () {
$(this).attr('name', $(this).attr('ci-name'));
});
});
});
Step 1:
Whenever a radio button is used in repeater, its groupname gets changed, since asp.net changes it so as to make it unique. Therefore each radio button gets different groupname (name attribute in client-side generated markup). Due to this, user is able to select all of the options at the same time. This issue is resolved by using jquery code as explained by subsequent comments.
Step 2:
This block of code creates a new custome attribute called ci-name and copies original value of name attribute into this new custom attribute. This process repeats for every radio button in poll. This step would help us in later step.
Step 3:
This block of code sets the value of name attributes of all radio buttons in poll to the value of name attribute of first radio button. This step prevents user from selecting more than one option at a time.
Step 4:
This code inside event handler of vote button click event, checks whether user has checked at least one option. If he hasn't, an error message is shown.
Step 5:
This code inside event handler of vote button click event, sets value of name attribute of all radio buttons to their original values. This is achieved by copying value from custom attribute ci-name. This allows asp.net server side code to know which button was actually clicked.
I was also baffled by this bug and decided to just drop the repeater in favor of dynamically building a table with the controls inside. In your user control or on your page, simply add the following elements:
<asp:Table ID="theTable" runat="server">
<asp:TableHeaderRow runat="server">
<asp:TableHeaderCell runat="server" Text="Column 1"/>
<asp:TableHeaderCell runat="server" Text="Column 2"/>
<asp:TableHeaderCell runat="server" Text="Column 3"/>
</asp:TableHeaderRow>
</asp:Table>
Then add the data rows in the code behind with radio buttons and other required controls. You can of course do the same with other elements like the DIV:
<div runat="server" ID=theDiv">
</div>
But let us still hope for the ASP.NET team to get around to fixing this unfortunate issue with repeaters and list views. I still like the repeater control and use it whenever possible.
This is a pure server side approach using reflection. The RadioButton control uses the UniqueGroupName property to determine the group name. The group name is cached inside the _uniqueGroupName field. By setting this field using reflection, we can override the default group name and use a group name that is the same across all radio buttons in a repeater. Please note this code must be run in the 'PreRender' event of the 'RadioButton' control to ensure the new group name is persisted across post backs.
protected void rbOption_PreRender(object sender, EventArgs e)
{
// Get the radio button.
RadioButton rbOption = (RadioButton) sender;
// Set the group name.
var groupNameField = typeof(RadioButton).GetField("_uniqueGroupName", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
groupNameField.SetValue(rbOption, "MyGroupName");
// Set the radio button to checked if it was selected at the last post back.
var groupValue = Request.Form["MyGroupName"];
if(rbOption.Attributes["value"] == groupValue)
{
rbOption.Checked = true;
}
}
RadioButton source code: http://reflector.webtropy.com/default.aspx/Net/Net/3#5#50727#3053/DEVDIV/depot/DevDiv/releases/whidbey/netfxsp/ndp/fx/src/xsp/System/Web/UI/WebControls/RadioButton#cs/2/RadioButton#cs
This may not be the ideal solution for everyone, but I did the following using jQuery.
<asp:RadioButton ID="rbtnButton1" groupName="Group1" runat="server" />
<asp:RadioButton ID="rbtnButton2" groupName="Group1" runat="server" />
etc...
Then include the following code in your master page. (or all your pages)
$(function() {
//This is a workaround for Microsoft's GroupName bug.
//Set the radio button's groupName attribute to make it work.
$('span[groupName] > input').click(function() {
var element = this;
var span = $(element).parent();
if (element.checked) {
var groupName = $(span).attr('groupName');
var inputs = $('span[groupName=' + groupName + '] > input')
inputs.each(function() {
if (element != this)
this.checked = false;
});
}
});
});
A custom control/override to work around the HtmlInputControl.RenderAttributes() method by ignoring the RenderedNameAttribute property:
/// <summary>
/// HACK: For Microsoft's bug whereby they mash-up value of the "name" attribute.
/// </summary>
public class NameFixHtmlInputRadioButton : HtmlInputRadioButton
{
protected override void RenderAttributes(HtmlTextWriter writer)
{
// BUG: Usage of 'HtmlInputControl.RenderedNameAttribute'
// writer.WriteAttribute("name", this.RenderedNameAttribute);
writer.WriteAttribute(#"name", Attributes[#"Name"]);
Attributes.Remove(#"name");
var flag = false;
var type = Type;
if (! string.IsNullOrEmpty(type))
{
writer.WriteAttribute(#"type", type);
Attributes.Remove(#"type");
flag = true;
}
base.RenderAttributes(writer);
if (flag && DesignMode)
{
Attributes.Add(#"type", type);
}
writer.Write(#" /");
}
}
I used same Technic to uncheck other radio with jquery please find below code
<asp:RadioButton ID="rbSelectShiptoShop" runat="server" onchange="UnCheckRadio(this);" CssClass="radioShop" />
and script below
function UnCheckRadio(obj) {
$('.radioShop input[type="radio"]').attr('checked', false);
$(obj).children().attr('checked', true);
}