How to change the value of input hidden on server-side - asp.net

I have a form with hidden fields:
<form id="Form1" runat="server" style="width: 100%; height: 100%; overflow: hidden" onsubmit="return false;">
<div>
<input type="hidden" runat="server" id="TrackColors" value=""/>
<input type="hidden" runat="server" id="Relogin" value=""/>
</div>
</form>
After Page_Load() on the server-side is called function:
protected void SomeFunction()
{
Dictionary<int, int> trackColors = new Dictionary<int, int>();
if (!String.IsNullOrEmpty(TrackColors.Value))
trackColors = ReadValues(TrackColors.Value);
//if value is null or empty it's assigned to a different
TrackColors.Attributes["value"] = FormValues(trackColors); //FormValues() return string
//change is visible
}
string FormValues(Dictionary<int, int> values)
{
string result = "";
if (values == null || values.Count == 0)
return result;
foreach (KeyValuePair<int, int> p in values)
result += p.Key + "##" + p.Value + "^^";
result = result.TrimEnd('^');
return result;
}
If I change the selected field of ComboBox, the function is called:
<dx:ASPxTextBox ID="ColorTrackCarID" Visible="false" Text='<%# Eval("CarId") %>' />
<dx:ASPxComboBox ID="ASPxComboBox1" runat="server" SelectedIndex='<%# Eval("TrackColor") %>'
ValueType="System.String" Width="30" ShowImageInEditBox="true"
ondatabinding="ASPxComboBox1_DataBinding">
<ClientSideEvents SelectedIndexChanged="function (s,e) {
if (window.TrackColorChanged != null)TrackColorChanged(s,e); }" />
</dx:ASPxComboBox>
function TrackColorChanged(s, e) {
var TrackColors = document.getElementById('TrackColors');
if (TrackColors == null || TrackColors.value == "")
return values;
//values is always emply
}
I understand the value of the form fields are not passed back to the client-side. The question is: How to pass these values ​​back?
And if I change the value on the server-side in Page_Load (), then the client can see everything, that is,
protected void Page_Load(object sender, EventArgs e)
{
TrackColors.Attributes["value"] = "bla-bla-bla";
//All changes are visible on the client-side
}
Thank you for your attention.

To make it even easier, replace your hidden fields with the control:
<asp:HiddenField id="X" runat="server" />
Which you can set the value on it directly:
X.Value = "XYZ";
This value can be passed from client to server, and vice versa, and works very easily. Not that you can't use a server-side input, but HiddenField handles a lot of that for you.
EDIT: Also, are you sure you're not overwriting the value? If you are doing this:
protected void Page_Load(object sender, EventArgs e)
{
TrackColors.Attributes["value"] = "bla-bla-bla";
//All changes are visible on the client-side
}
This will always change the value to "bla-bla-bla". You would want to wrap it in if (!Page.IsPostback) if you initialize it on page load.

Related

Radio button doesn't get selected after a post back

I have an item template within repeater:
<ItemTemplate>
<li>
<input type="radio"
value="<%# GetAssetId((Guid) (Container.DataItem)) %>"
name="AssetId"
<%# SelectAsset((Guid) Container.DataItem) %> />
</li>
</ItemTemplate>
I have a method that compares ids and decides whether to check the radio button.
protected string SelectAsset(Guid uniqueId)
{
if (uniqueId == GetSomeId())
return "checked=\"checked\"";
return string.Empty;
}
SelectAsset gets hit, but it doesn't select a radio button on a post back, but it does work if I just refresh the page. What am I doing wrong here?
Answer here: How to display "selected radio button" after refresh? says that it's not possible to achieve, is this really the case?
Thank you
Update
It appears that view state isn't available for simple controls if they don't have a runat attribute. I have solved this by using a custom GroupRadioButton control. Thank you for your help.
I'd suggest using a RadioButtonList:
Page Code
<asp:RadioButtonList RepeatLayout="UnorderedList" OnSelectedIndexChanged="IndexChanged" AutoPostBack="true" ID="RadioRepeater" runat="server" />
<asp:Label ID="SelectedRadioLabel" runat="server" />
Code Behind
if (!Page.IsPostBack)
{
/* example adds items manually
- you could iterate your datasource here as well */
this.RadioRepeater.Items.Add(new ListItem("Foo"));
this.RadioRepeater.Items.Add(new ListItem("Bar"));
this.RadioRepeater.Items.Add(new ListItem("Baz"));
this.RadioRepeater.SelectedIndex = this.RadioRepeater.Items.IndexOf(new ListItem("Bar"));
this.RadioRepeater.DataBind();
}
protected void IndexChanged(object sender, EventArgs e)
{
this.SelectedRadioLabel.Text = string.Format("Selected Item Text: {0}", this.RadioRepeater.SelectedItem.Text);
}
I assume you only need to select one item.
As described in the comments, it even works to access the SelectedItem in the Page_Loadevent handler:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// previous code omitted
}
else
{
string foo = this.RadioRepeater.SelectedItem.Text;
}
}
If you are creating all your controls dynamically at run-time (directly from code), then things are a little different. Here is the code that I used:
Page Code
<form id="form1" runat="server">
</form>
Code Behind
protected void Page_Load(object sender, EventArgs e)
{
RadioButtonList rbl = new RadioButtonList();
rbl.AutoPostBack = true;
rbl.SelectedIndexChanged += rbl_SelectedIndexChanged;
rbl.Items.Add("All");
// generate your dynamic radio buttons here
for (int i = 0; i<5; i++)
{
rbl.Items.Add(string.Format("Dynamic{0}", i));
}
form1.Controls.Add(rbl);
if (!Page.IsPostBack)
{
rbl.SelectedValue = "All";
PopulateTextBox(rbl.SelectedValue);
}
}
void rbl_SelectedIndexChanged(object sender, EventArgs e)
{
RadioButtonList foo = (RadioButtonList)sender;
PopulateTextBox(foo.SelectedValue);
}
void PopulateTextBox(string selection)
{
TextBox box = new TextBox();
box.Text = selection;
form1.Controls.Add(box);
}

Populate ASPxTextBox and ASPxListBox from Code Behind

im using the Devexpress ASPxGridView for a project but are having problems to populate a custom EditForm with data.
It looks as follows
<Templates>
<EditForm>
Company Name:
<dx:ASPxTextBox ID="CompanyName" runat="server" Value="<% #Bind('CompanyName') %>" />
Parent:
<dx:ASPxListBox ID="ParentGuid" runat="server" Value="<% #Bind('ParentGuid') %>" />
</EditForm>
</Templates>
Normally I'd write something like
protected void ASPxGridView1_StartRowEditing(object sender, DevExpress.Web.Data.ASPxStartRowEditingEventArgs e)
{
var CompanyList = db.companies.OrderBy(x => x.CompanyName).ToList();
ASPxListBox ParentGuid = (ASPxListBox)ASPxGridView1.FindControl("ParentGuid");
ParentGuid.DataSource = CompanyList;
ParentGuid.DataBind();
ASPxTextBox CompanyName = (ASPxTextBox)ASPxGridView1.FindControl("CompanyName");
CompanyName.Text = "Some company name";
}
But that wont work. Any advice where to start? The documentation doesn't really cover custom forms that well :/
Thanks!
== UPDATE ==
Tried using the onhtmleditformcreated="ASPxGridView1_HtmlEditFormCreated" with the method
protected void ASPxGridView1_HtmlEditFormCreated(object sender, ASPxGridViewEditFormEventArgs e)
{
Control CompanyName = ASPxGridView1.FindEditFormTemplateControl("CompanyName");
if (CompanyName != null)
{
ASPxTextBox CompanyNameEdit = CompanyName as ASPxTextBox;
CompanyName.Text = "Some Co";
}
}
The fact that I use Value="<% #Bind('CompanyName') %>" messes stuff up a bit. If i remove the Bind the boxes gets populated but then I have no way of fetching the data in them. Any way around this?
You should use a slightly different approach:
Use the HtmlEditFormCreated event to set editors properties. To obtain editor instances, use the gridView's FindEditFormTemplateControl method.
The answer is...
To populate a ASPxComboBox called CompanyList
protected void ASPxGridView1_HtmlEditFormCreated(object sender, ASPxGridViewEditFormEventArgs e)
{
Control ParentGuidControl = ASPxGridView1.FindEditFormTemplateControl("ParentGuid");
if (ParentGuidControl != null)
{
ASPxComboBox ParentGuid = (ASPxComboBox)ParentGuidControl;
var CompanyList = db.companies.OrderBy(x => x.CompanyName);
ParentGuid.TextField = "CompanyName";
ParentGuid.ValueField = "CompanyGuid";
ParentGuid.DataSource = CompanyList;
ParentGuid.DataBind();
}
}
BUT!
If you have a custom form like i had
<Templates>
<EditForm>
Company Name:
<dx:ASPxTextBox ID="CompanyName" runat="server" Value="<% #Bind('CompanyName') %>" />
Parent:
<dx:ASPxComboBox ID="ParentGuid" runat="server" Value="<% #Bind('ParentGuid') %>" />
</EditForm>
</Templates>
you wont be able to populate it from code-behind, the #bind method is in the way and overwrite any other incoming value. However if you are not planning to populate them from code behind here is a neat trick to fetch the data...
protected void ASPxGridView1_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
{
IDictionaryEnumerator enumerator = e.NewValues.GetEnumerator();
string CompanyName = string.Empty;
Guid ParentGuid = Guid.Empty;
enumerator.Reset();
while (enumerator.MoveNext())
if (enumerator.Key.ToString() == "CompanyName")
CompanyName = enumerator.Value.ToString();
else if (enumerator.Key.ToString() == "ParentGuid")
ParentGuid = new Guid(enumerator.Value.ToString());
// Do insert trick here
}
But if you want to fill some of the form values from code-behind ensure there are no #bind methods in the EditForm
<Templates>
<EditForm>
Company Name:
<dx:ASPxTextBox ID="CompanyName" runat="server" />
Parent:
<dx:ASPxComboBox ID="ParentGuid" runat="server" />
</EditForm>
</Templates>
Populate as described in the top of this post and fetch the values like this
protected void ASPxGridView1_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
{
string CompanyName = string.Empty;
Guid ParentGuid = Guid.Empty;
// This method is a bit more secure
Control CompanyNameControl = ASPxGridView1.FindEditFormTemplateControl("CompanyName");
if (CompanyNameControl != null)
{
ASPxTextBox CompanyNameTb = (ASPxTextBox)CompanyNameControl;
CompanyName = CompanyNameTb.Text.ToString();
}
// A bit less secure, but lesser code
ASPxComboBox ParentGuidControl = (ASPxComboBox)ASPxGridView1.FindEditFormTemplateControl("ParentGuid");
ParentGuid = new Guid(ParentGuidControl.SelectedItem.Value.ToString());
// Do insert...
}
Have fun

RadioButtonList Postback Issues

Environment: ASP NET 2.0 - Production Server does not have Ajax Control Toolkit so no real Control toolkit to use here.
3 RadioButtons List:
List one loads, after postback, the item from list one is used to select a Lab value.
Once a lab value is selected a 3rd radiobuttonlist will populate. There are some textboxes but they are not shown in example. The textboxes postback themselves on changes. If both textboxes are
not empty, a record is created for the session.
Now if the 3rd radiobuttonlist is changed from the default a series of 3 hidden user controls appear which represent 3 levels of reasons for the change ( child/parent records in database ).
The problem I am having is when I select a different item on the radiobuttonlist the radiobutton 3 OnSelectedIndex is firing after my user controls fire. My user controls need the value of the 3rd list to go to the database and get the correct set of records associated with the lab.
The problem is because the last radiobuttonlist is not processed until after the web controls loads, the code to mount the user controls never happens.
Here is the basic HTML code:
<asp:RadioButtonList ID="rdoLab" runat="server" OnSelectedIndexChanged="rdoLab_OnSelectedIndexChange">
</asp:RadioButtonList>
<asp:TextBox ID="textbox1" runat="server" OnTextChanged="TextBoxProcess" />
<asp:TextBox ID="textbox2" runat="server" OnTextChanged="TextBoxProcess" />
<asp:RadioButtonList ID="rdoPrimary" RepeatColumns="3" OnSelectedIndexChanged="rdoPrimary_OnSelectedIndexChanged" runat="server" ToolTip="Select Normal, Hypo or Hyper - Normal is default value." AutoPostBack="True" >
<asp:ListItem Value="3" Text="Normal" Selected="true"/>
<asp:ListItem Value="1" Text="Hypo" />
<asp:ListItem Value="2" Text="Hyper" />
</asp:RadioButtonList>
<asp:Panel ID="UpdLab" runat="server" Visible="true" EnableViewState="true">
<asp:Table ID="tblAdmin" runat="server">
<asp:TableRow>
<asp:TableCell runat="server" id="tblCell1" Visible="false" CssClass="tdCell" VerticalAlign="top">
<uc1:Lab ID="Lab1" runat="server" EnableViewState="true" EnableTheming="true" />
</asp:TableCell>
<asp:TableCell runat="server" ID="tblCell2" Visible="false" CssClass="tdCell" VerticalAlign="top">
<uc1:Lab ID="Lab2" runat="server" EnableViewState="true" EnableTheming="true" />
</asp:TableCell>
<asp:TableCell runat="server" ID="tblCell3" Visible="false" CssClass="tdCell" VerticalAlign="top">
<uc1:Lab ID="Lab3" runat="server" EnableViewState="true" EnableTheming="true" />
</asp:TableCell>
</asp:TableRow>
</asp:Table>
</asp:Panel>
Here is the page behind:
protected override void OnPreLoad(EventArgs e)
{
base.OnPreLoad(e);
GetSessionVars();
if (CommonUI.strTest((string)Session["rdoLabs"]) && CommonUI.strTest((string)Session["rdoPrimary"]) && Convert.ToString(hrdoLabs.Value) == (string)Session["rdoLabs"])
{
divLabLvl.Visible = true;
// Get cboListItems from the web user controls...
Session["ArrLstItems"] = "";
ArrayList ArrLstItems = new ArrayList();
ArrayList GetWuc = GetWUCS();
for (int i = 0; i < GetWuc.Count; i++)
{
Lab wuc = (Lab)GetWuc[i];
CheckBoxList cboItemList = (CheckBoxList)wuc.FindControl("cboItems");
string cboItems = GetCboItemList(cboItemList);
HiddenField hcboItems = (HiddenField)wuc.FindControl("hcboItems");
}
Session["ArrLstItems"] = (ArrayList)ArrLstItems;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DbDataReader ddrGrp = rdoGroups();
if (ddrGrp.HasRows)
{
rdoGroup.DataSource = ddrGrp;
rdoGroup.DataBind();
}
ddrGrp.Close();
}
else
{
DbDataReader ddrLab = rdoUserLabs();
if (ddrLab.HasRows)
{
rdoLabs.DataSource = ddrLab;
rdoLabs.DataBind();
if (CommonUI.strTest((string)Session["rdoLabs"]))
{
if (Convert.ToInt32(Session["rdoLabs"]) > 0)
{
rdoLabs.SelectedValue = (string)Session["rdoLabs"];
SetLabCss();
}
}
}
ddrLab.Close();
}
}
protected void rdoGroup_OnSelectedIndexChanged(object sender, EventArgs e)
{
//...do some stuff
}
protected void rdoLabs_OnSelectedIndexChanged(object sender, EventArgs e)
{
//... reload
}
protected DbDataReader rdoGroups()
{
int group_type_id = GroupTypeId();
Group grp = new Group();
return grp.GetGroups(group_type_id);
}
protected DbDataReader rdoUserLabs()
{
RadioButtonList rdoGrp = (RadioButtonList)CommonUI.FindCtrlRecursive(this.Master, "rdoGroup");
int GroupId = Convert.ToInt32(rdoGrp.SelectedValue);
LabAbnormalReasons lar = new LabAbnormalReasons();
return lar.GetLabsList(GroupId);
}
protected void rdoPrimary_OnSelectedIndexChanged(object sender, EventArgs e)
{
Session["Save"] = ((RadioButtonList)sender).ID;
RadioButtonList rdoGroups = (RadioButtonList)CommonUI.FindCtrlRecursive(this.Master, "rdoGroup");
RadioButtonList rdoLabs = (RadioButtonList)CommonUI.FindCtrlRecursive(this.Master, "rdoLabs");
int UserId = Convert.ToInt32(Session["UserId"]);
int DocId = Convert.ToInt32(Session["DocId"]);
SubmitLab_Data(arrLstItems, arrOthers);
}
protected void GetSessionVars()
{
RadioButtonList rdoGroup = (RadioButtonList)CommonUI.FindCtrlRecursive(this.Master, "rdoGroup");
RadioButtonList rdoPrimary = (RadioButtonList)CommonUI.FindCtrlRecursive(this.Master, "rdoPrimary");
RadioButtonList rdoLabs = (RadioButtonList)CommonUI.FindCtrlRecursive(this.Master, "rdoLabs");
if (rdoGroup.SelectedIndex != -1)
{
Session["rdoGroup"] = (string)rdoGroup.SelectedValue;
}
if (rdoLabs.SelectedIndex != -1)
{
Session["rdoLabs"] = (string)rdoLabs.SelectedValue;
}
if (rdoPrimary.SelectedIndex != -1)
{
Session["rdoPrimary"] = (string)rdoPrimary.SelectedValue;
}
}
Here is example of user code:
THIS CODE NEVER FIRES BECAUSE the 3rd Button List data is not available here :
protected void Page_Load(object sender, EventArgs e)
{
/////*
//// * lab & Primary have been selected...
//// */
int lvl = SetLvlId();
int par_id = GetParentLvl();
Lab wuc = GetWuc(lvl);
if (wuc != null)
{
if (CommonUI.strTest(Convert.ToString(Session["rdoLabs"])) && CommonUI.strTest(Convert.ToString(Session["rdoPrimary"])))
{
// data in data base for this user, lab, doc identifier...
if (Convert.ToInt32(Session["rdoPrimary"]) > 0
{
// have user hdr data - see if item data is mapped...
// do some stuff here
}
}
}
}
I hope this is clear. I've att
---*--- Since original posting:
added simple javascript/OnDataBound
function Primary(object)
{
alert("Value Clicked :" + object);
}
protected void rdoPrimary_DataBound(object sender, EventArgs e)
{
RadioButtonList rdlPrimary = (RadioButtonList)sender;
foreach (ListItem li in rdlPrimary.Items)
{
li.Attributes.Add("onclick", "javascript:Primary('" + li.Value + "')");
}
}
Store and retrieve the values you want to retain in SaveViewState and LoadViewState methods and see if that works for you? Also look to the earlier and later lifecycle events for handling the logic - Init and OnPreRender. This has worked for me in the past.

ASP.Net dropdown control loses state after being set dynamically through javascript

I have an asp.net dropdownlist control. There are two ways it can be selected.
The first is through a button that sets the value in the drop-down list via javascript.
The second is by manually selecting the dropdownlist option.
Each of these methods work by themselves.
If I do the first followed by the second and then hit save - the value that is saved is the value set by the javascript. The manual selection did not have any effect.
Does anyone know why this is the case?
EDIT:
In the HTML Head section:
<script>
function Select(allocationId) {
document.getElementById('Accounts').value=allocationId;
}
</script>
In the HTML Body:
<asp:DropDownList ID="Accounts" runat="server"></asp:DropDownList>
<button onclick="Select(<%#"'" + DataBinder.Eval(Container.DataItem, "Associated_AccountId") + "'"%>)" type="button">Select</button>
<asp:Button ID="btn_SaveAndClose" runat="server" Text="Save and Close" OnClick="btn_SaveAndClose_Click"></asp:Button>
In the code behind:
protected void btn_SaveAndClose_Click(object sender, System.EventArgs e)
{
int id = Convert.ToInt32(this.Accounts.SelectedValue);
}
EDIT:
Funnily enough - when I use:
int id = Convert.ToInt32(Request.Form["Accounts"]);
it works. But I don't know why.
The most common mistake that would cause this is that you're likely populating or binding that DropDownList every Page_Load or Init, thus erasing whatever state you entered the page with. Be sure to do a (!IsPostBack) check before populating your DropDownList.
This worked for me: (try removing the !IsPostBack check and see if the behavior is similar to what you're seeing in your app)
page content
<asp:DropDownList ID="ddlTest" runat="server"></asp:DropDownList>
<button onclick="select(3);">Select Three</button>
<asp:Button ID="btnSave" runat="server" OnClick="btnSave_Click" Text="Save" />
<script type="text/javascript" language="javascript">
//<![CDATA[
function select(value) {
var ddlTest = document.getElementById('<%=ddlTest.ClientID%>');
for (var i = 0; i < ddlTest.options.length; i++) {
if (ddlTest.options[i].value == value) {
ddlTest.selectedIndex = i;
return;
}
}
}
//]]>
</script>
<asp:Label ID="lblResult" runat="server"></asp:Label>
Code Behind
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
PopulateDropDown();
}
protected void btnSave_Click(object sender, EventArgs e)
{
lblResult.Text = ddlTest.SelectedValue;
}
void PopulateDropDown()
{
Dictionary<int, string> data = new Dictionary<int, string>();
data.Add(1, "One");
data.Add(2, "Two");
data.Add(3, "Three");
ddlTest.DataSource = data;
ddlTest.DataTextField = "Value";
ddlTest.DataValueField = "Key";
ddlTest.DataBind();
}

Two text boxes, either one or both are required

I have two textboxes on an asp.net webpage, either one or both are required to be filled in. Both cannot be left blank. How do I create a validator to do this in asp.net?
You'd need a CustomValidator to accomplish that.
Here is some code demonstrating basic usage. The custom validator text will show after IsValid is called in the submit callback and some text will be displayed from the Response.Write call.
ASPX
<asp:TextBox runat="server" ID="tb1" />
<asp:TextBox runat="server" ID="tb2" />
<asp:CustomValidator id="CustomValidator1" runat="server"
OnServerValidate="TextValidate"
Display="Dynamic"
ErrorMessage="One of the text boxes must have valid input.">
</asp:CustomValidator>
<asp:Button runat="server" ID="uxSubmit" Text="Submit" />
Code Behind
protected void Page_Load(object sender, EventArgs e)
{
uxSubmit.Click += new EventHandler(uxSubmit_Click);
}
void uxSubmit_Click(object sender, EventArgs e)
{
Response.Write("Page is " + (Page.IsValid ? "" : "NOT ") + "Valid");
}
protected void TextValidate(object source, ServerValidateEventArgs args)
{
args.IsValid = (tb1.Text.Length > 0 || tb2.Text.Length > 0);
}
Try a CustomValidator.
You'll need to create a method that does the following to handle the ServerValidate event:
void ServerValidation (object source, ServerValidateEventArgs args)
{
args.IsValid = TextBox1.Text.Length > 0 || TextBox2.Text.Length > 0;
}
In addition to creating server-side validation, you can use the ClientValidationFunction property on the CustomValidator to provide client-side validation as well. That might look something like this:
function(sender, args) {
args.IsValid = document.getElementById('<%=TextBox1.ClientID%>').value != ''
|| document.getElementById('<%=TextBox2.ClientID%>').value != '';
}
Onclientclick of your button or whatever submits your page call a javascript function like this
function valtxtbox(){
if (document.getElementById('<%=TextBox1.ClientID%>').value== '' && document.getElementById('<%=TextBox2.ClientID%>').value== '')
{
alert('You must enter in data!');
return false;
}

Resources