format for url to point to radio button selection [duplicate] - asp.net

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
linking to a radio button selection, asp.net c#
i have a page with a textarea and radio buttons. the text area is populated with data based on the radio button selection. i want the radio button selection to appear in the url so that a user can link to the radio button selection.
i'm hoping that all i need to do i modify my querystring to include radio button value. here's the data caputered by fidler when i make a radio button selection.
__EVENTTARGET ctl00$MainContent$RadioButtonList1$6
__EVENTARGUMENT
__LASTFOCUS
__VIEWSTATE /+++PC9wPg0KPHA+/....
__EVENTVALIDATION /wEWCwKY7d6oAQLh8vmTCALk7M7lDQK+6NunDwK/6OenDwK86OenDwK86OunDwK86POnDwK96NenDwK96NunDwKxh73KA3Q+PMuKU/JUCKsF1aiY2DNLu7/pFFni/Qtz+7FXy35g
ctl00$MainContent$RadioButtonList1 41
i'm hoping my url simply needs to look something like this to point to the radio button value but and all i need is the appropriate syntax:
http://www.test.com/test.aspx?ctl00$MainContent$RadioButtonList1$41
---code behind ---
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false)
{
RadioButtonList1.SelectedIndex = 0;
RadioButtonList1.DataBind();
}
else
{
string strRedirect;
strRedirect = "frm_Articles.aspx?Article_PK=" + RadioButtonList1.SelectedValue.ToString();
Response.Redirect(strRedirect);
}
}
protected void SqlDataSource2_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
//
}
protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
try{
e.Command.Parameters["#URL_FK"].Value = Session["URL_PK"];
}
catch (Exception ex)
{
}
}
}

One thing to note is that you have misconstructed your url. It should be:
http://www.test.com/test.aspx?ctl00$MainContent$RadioButtonList1=41
(note the third to last character is an =.
Apart from that it would depend on how your page works in terms of picking up the selected radio button. My advice would be to just try it and see what happens. However, I would suspect that if you are doing it based on an event firing on page load (ie some kind of postback behaviour) then it won't work.
If this is the case then you will just want to do something on page load to check if that value exists in the url and set it before you load up the text. If you end up going down this route you might want to consider using a more well defined and user friendly querystring parameter. In particular the id you have there is built based on its position in the control hierarchy. If you were to redesign your HTML structure the ID might well change.
Additionally...
With the code you've provided where you set the selectedindex of your radiobutton list you need to find out what value you need before you set it and set it to 0 if you have no better value (though it looks like you are setting to 0 before binding whcih seems superfluous). Something like this may work (not compiled or tested so apologies for typos - it is designed to give you the general idea more than to be finalised code).
if (Page.IsPostBack == false)
{
RadioButtonList1.DataBind();
//Check if you have a value to set.
if (Request.Querystring(RadioButtonList1.ClientID)!=null)
{
//Get the value
string setValue = Request.Querystring(RadioButtonList1.ClientID)
//Find the right radio option to select
foreach(ListItem item in RadioButtonList1.Items)
{
if (item.Value == setValue)
{
item.Selected = true;
break;
}
}
}
}
I assume it will default to the selected index being 0 if nothing is set as selected otherwise.
Anyway, this code is meant as a starting point to work from. There may be other ways to do it and some may even be better.

Related

Populate form with values then saved modified values with C# using asp.net webforms

My .NET skills aren't great, but I'm stumped by a little issue and I can't find anything that explains this in a way I understand. Basically I'm trying to pre-populate a form with current values from a CMS, and have those values able to be updated when the form is submitted. It's essentially just an 'edit' facility for part of a website.
I have a usercontrol which contains some form inputs like this:
<label for="">Raised by</label>
<asp:TextBox ID="RaisedBy" runat="server"></asp:TextBox>
I then have a code-behind page which pulls values from a CMS and populates this form with the values already stored for this record, like this:
protected void Page_Load(object sender, EventArgs e)
{
// ...Some logic here gets the node from the CMS and I can pull property values from it. This part works fine.
string raisedBy = node.GetProperty("raisedBy").ToString();
// Populate form input with value from CMS. This works.
RaisedBy.Text = raisedBy;
}
So this is fine. But when the form is submitted it calls the following code:
protected void edit_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
// Get edited value of input field
string RaisedByVal = RaisedBy.Text;
// Do some logic here to set up the CMS to be able to save the property - this works although it uses the original value of the form not the modified value if the user has changed it.
pageToEdit.getProperty("raisedBy").Value = RaisedByVal;
}
}
The problem is that the original form values are being saved back to the system rather than the modified values if the user has edited them.
Can anyone suggest what I'm doing wrong and how to get the modified values to be used rather than the original values?
Many thanks.
You have to check whether it is Postback or not in Page_Load() method:
So if you don't do this then on edit button click it will 1st call the Page_Load() and will again reset the original value. Later it will call the Edit click method and you will still see the original data.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// ...Some logic here gets the node from the CMS and I can pull
property values from it. This part works fine.
string raisedBy = node.GetProperty("raisedBy").ToString();
// Populate form input with value from CMS. This works.
RaisedBy.Text = raisedBy;
}
}
Typically I found the answer right after posting! :)
I needed to wrap the 'pre-populate form values' logic inside a:
if (!IsPostBack)
{
}
block.

jqgrid asp.net webforms Server side SelectedRow property empty

I am trying to get this sample to work
Get Selected Row (on server)
but for me the SelectedRow property is always empty.
The only difference being that I am using the Page_load event to populate my grid.
When i press a button on my form, it does a postback, and repopulates the grid losing the row selection.
sample code:
if (!Page.IsPostBack )
{
UserBusinessObject userBO = new UserBusinessObject();
GRDUsers.DataSource = userBO.GetUsersbyProfileID(SessionFacade.Id);
GRDUsers.DataBind();
}
protected void btnEdit_Click(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(GRDUsers.SelectedRow))
{
lblError.Visible = true;
}
else
{
Response.Redirect(string.Format("~/Manage/EditUserRoles.aspx?username={0}",GRDUsers.SelectedRow));
}
}
I Have also noticed that on button click, my Page Load fires twice (1st time postback is true, 2nd time it is false) According to jqgrid posts this is intentional. but i think this might be causing my grief.
You always must set the DataSource because is not saved on ViewState or anywhere else. So the code must be as:
UserBusinessObject userBO = new UserBusinessObject();
GRDUsers.DataSource = userBO.GetUsersbyProfileID(SessionFacade.Id);
if (!Page.IsPostBack )
{
GRDUsers.DataBind();
}
working with the guys at JQGrid, we have resolved the problem. It is a bug in their grid that has been fixed in v4.5.0.0
see here for details
i can confirm that this fixes the bug, and all is right with the world again

Retrieving and updating server control values in a ListView

In the past I've used jQuery Ajax to create a shopping cart. This time around I'm using the list view server control.
If I have a qty text box in each row and I want to update the quantity on a button click is this the most elegant way to achieve this?
protected void Button1_Click(object sender, EventArgs e)
{
foreach(ListViewItem item in ListViewCart.Items)
{
foreach (Control con in item.Controls)
{
if (con.GetType() == typeof(TextBox))
{
//Do Work.
}
}
}
}
I'm guessing that I would need to store the productID in a custom attribute for each textbox and use it when updating the database. (Or write more code to find that value somewhere else in the row.)
More importantly, is there a different server control I might want to use instead? I don't want to use the gridview.
I guess you could shorten it a little bit like this
foreach (TextBox txtBox in
ListViewCart.Items.SelectMany(item => item.Controls.OfType<TextBox>()))
{
//do work like - txtBox.Text = "foo";
}

How to get the latest selected value from a checkbox list?

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.

Javascript for disabling dropdown in ASP.NET

I am using JScript in ASP.NET 2005. I have a page with a checkbox and a dropdown list. When the checkbox is checked, the dropdown is to be disabled. During Postback of the page, this behavior should be retained. I am using a javascript function as follows
if((chkOwner[1].checked==true))
{
document.getElementById(ddlClientID).disabled=true;
document.getElementById(ddlClientID).className = "form-disabled";
document.getElementById(ddlClientID).selectedIndex = 0;
}
else
{
document.getElementById(ddlClientID).disabled=false;
document.getElementById(ddlClientID).className = "form-input";
document.getElementById(ddlClientID).selectedIndex = 0;
}
This works, almost. However, the dropdown selection is not retained after postback (when checkbox is not selected). [It goes to zero index's value]
Apprently the solution is to remove the last line, i.e, in the else part, remove the selectedIndex =0 .
But, when I do that the disabling of dropdown (when check box is checked) is not working after post back.
Could you please help me on this?
More Info: I am using ClientScript.RegisterStartupScript for checking this at each page load.
Thanks
Lijo
--CODE-----
Following is what I am trying. (This is a sample application I created just now. It does not work. This can only show what I am trying to achieve.)
function ManageInputsFor()
{
if((document.getElementById(chbx).checked==true))
{
document.getElementById(ddlClientID).disabled=true;
document.getElementById(ddlClientID).className = "form-disabled";
document.getElementById(ddlClientID).selectedIndex = 0;
}
else
{
document.getElementById(ddlClientID).disabled=false;
document.getElementById(ddlClientID).className = "form-input";
document.getElementById(ddlClientID).selectedIndex = 0;
}
}
protected void Page_Load(object sender, EventArgs e)
{
ClientScript.RegisterClientScriptBlock(Page.GetType(), "chbx", #"<script language=""javascript"" type=""text/javascript"">var chbx ='" + CheckBox1.ClientID + "'</script>");
ClientScript.RegisterClientScriptBlock(Page.GetType(), "ddl", #"<script language=""javascript"" type=""text/javascript"">var ddlClientID ='" + DropDownList1.ClientID + "'</script>");
ClientScript.RegisterStartupScript(Page.GetType(), "onLoadCallForManageInputs", #"<script language=""javascript"" type=""text/javascript"">ManageInputsFor();</script>");
CheckBox1.Attributes.Add("onclick", "ManageInputsFor();");
}
you'll have to do a server side evaluation of the checkbox during the pastback, and set the dropdownlist enabled or not. the disabled attribute of the drop down isn't sent to the server during the post operation (neither is the value of the control when it's disabled,btw).
edit: to retain the value in the drop down across a postback, you can copy the selected value to another control which will be posted back, and then assign the value back to the drop down during server processing.
Basically, your problem is happening bc when you use javascript to change the state of an ASP control, that stat is not posted back to the server. You have to figure out a way to send it. Using a hidden control, or adding a parameter to the querystring are two such methods.

Resources