I try to save on Onclientclick to my hiddenfield a string value but it doesnt work I think because of Server.Transfer();
In my is only one control for postback(Dropdownlist) if I change dropdown value I get work Server.Transfer at last in my code.
Here is the code :
$(document).ready(function () {
alert($("[id*=hdnSelectedDiv]").val());
});
function SaveDiv(value) {
$("[id*=hdnSelectedDiv]").val(value);
}
<asp:LinkButton runat="server" CssClass="card-link" ID="lnkGoToLogin" OnClientClick="SaveDiv('dvLogin');return false;" meta:resourcekey="lnkGoToLoginRes"></asp:LinkButton></p>
Here is my OnSelectedIndexChanged :
CurrentSession.SetCurrentLanguage(ddl.SelectedValue);
ddl.SelectedValue = CurrentSession.CurrentLanguage.IetfLanguageTag;
Thread.CurrentThread.CurrentCulture = new CultureInfo(ddl.SelectedValue);
Thread.CurrentThread.CurrentUICulture = new CultureInfo(ddl.SelectedValue);
Server.Transfer(Request.Url.AbsolutePath);
On document ready alert is my value always empty.I try to set value on my document and alert the value it is working.but if I click linkbutton and select any option in my dropdown after postback is my value empty.
How can I solve this I dont want to use Response.Redirect();
That hidden field must have name property.
When the postback occurs, within the server code, is the moment when you can retrieve posted values. This is the time to process them - because, after Server.Transfer starts executing, source context is gone. If you need those values within the target request (the handler transferred to), you need to pass them to it. Your options are: persisted storage (e.g. database), session (might be the best in your case), query.
Related
Saving the values in the Lists & works fine.
abc= (ABC)(Session["xml"]);
string ctrlStr = String.Empty;
foreach (string ctl in Page.Request.Form)
{
if (ctl.Contains("something"))
{
ctrlStr = ctl.ToString();
abc.student[0].marks[j].science.something.Value = Convert.ToDecimal(Request.Form[ctrlStr]);
}
Want to retrieve the values from the saved object when I click on edit button back on the respective dynamic textboxes....
foreach (string ctl in Page.Request.Form)
{
if (ctl.Contains("studentname"))
{
ctrlStr = ctl.ToString();
(Request.Form[ctrlStr]) = abc.student[0].marks[x].science.studentname.ToString();---Gives an error stating the collection is only readonly
}
}
Request.Form — like the Request object generally — is read-only, reflecting the fact that, by the time you are responding to a request, the request itself cannot be changed. ASP.NET uses the values from the form POST to create server controls on the Page, and these allow you to control the values of the input and other form elements that are written to the Response object.
In your case, the TextBox controls are being generated dynamically, so they are not automatically bound to form values — hence your problem. You will need to keep references to the controls when they are created (or find them afterwards using the FindControl() method) and set their Text property.
(original answer follows)
The Controls collection becomes read-only at a certain point in the construction of the page. You have to do manipulation before that point. I don't remember offhand when it is, but you're safe with OnLoad through OnPreRender.
Where is your code firing from?
Update: Okay, I see what you're trying to do. This will be easiest if you're dealing with server-side controls (that is, controls generated by ASP.NET. That would look like this in your aspx (or ascx):
<asp:TextBox runat="server" ID="studentname"/>
Then you could update the value like this:
abc = (ABC)(Session["xml"]);
studentname.Text = abc.student[0].marks[j].science.something.Value.ToString();
That will set the value of the studentname text box automatically without needing to search through all of the Request.Form items. (Assuming you set j somewhere... I don't know the context for that.)
I can't tell for sure from your code, but it looks like you may just have a "plan HTML" input, which would look more like this:
<input type="text" name="studentname"/>
In that case, there is no simple way to update the value from your page's code, so I'd start by making sure that you're using server-side controls.
You can set the Request.Form values with reflection:
Request.Form.GetType().BaseType.BaseType.GetField("_readOnly", BindingFlags.NonPublic | BindingFlags.Instance)
.SetValue(Request.Form, false);
Request.Form["foo"] = "bar";
What you are trying to achieve?
The Form collection retrieves the values of form elements posted to the HTTP request body, with a form using the POST method. - http://msdn.microsoft.com/en-us/library/ms525985(v=vs.90).aspx
This is my first web page ever and I can't seem to find the correct way to get the selected index from a dropdown list. I don't need the selected index until the user presses the submit button. I've been testing everything I've found on the subject, but nothing is working.
I don't want the drop-down box to reset when the selection is made, which is what happens if I use postback=true or any selected index changed events. And, I still get an index of 0.
When I test, the selected index is always zero.
This runs on page load:
ddlBudgetLineItem.DataSource = budget.BudgetLineItems;
ddlBudgetLineItem.DataTextField = "Name";
ddlBudgetLineItem.DataValueField = "BudgetLineItemID";
ddlBudgetLineItem.DataBind();
This is the drop-down list:
<asp:DropDownList ID="ddlBudgetLineItem" runat="server">
</asp:DropDownList>
Here is the code that needs the index:
protected void submitPayment()
{
string amountValue = txtAmount.Text.ToString();
float amount = float.Parse(amountValue);
Payment payment = new Payment()
{
Amount = amount,
Payee = txtPayee.Text,
BudgetLineItem = budget.BudgetLineItems[ddlBudgetLineItem.SelectedIndex],
Memo = txtMemo.Text,
PaymentDate = DateTime.Parse(txtPaymentDate.Text),
ExtraUserInfo = info
};
provider.AddPayment(payment);
}
Any assistance is appreciated.
it seems to be a life cycle issue, this is happening because everytime (on a postback or not) the page is loaded, your dropdown is rebuilt (caused by ddlBudgetLineItem.DataBind()), concluding that on a postback your ddl will get index=0 forever.
how can you solve this:
1: Override the page databind method and put your code before call base.databind(); (inside the method)
2: on your load event you just have to call databind (if not is postback), it prevent to rebuild your object states everytime your page is loaded.(cause of your lost information).
3: take a look on a page lifecycle it will help you to prevent future issues like that.
I write an imagebutton to a table cell in a new row when a user selects an item in a list:
ImageButton imgbtnRemove = new ImageButton();
imgbtnRemove.ID = "uxStandardLetterDeleteImage_" + items.letterName;
imgbtnRemove.CommandName = "uxStandardLetterDeleteImage_" + items.letterName;
imgbtnRemove.ImageUrl = items.remove;
imgStatus.AlternateText = "Remove";
tRow.Cells[3].Controls.Add(imgbtnRemove);
When the new imagebutton is clicked, I can't seem to get a handle to it. I see it in Page_PreRender event, where I also reload the table on each postback.
string returnData = Request.Form.ToString();
but iterating through the form controls images:
if (c is System.Web.UI.WebControls.Button ||
c is System.Web.UI.WebControls.ImageButton)
does not find it. I can find it if I manually put in a:
imgbtnRemove.Click += new System.Web.UI.ImageClickEventHandler(this.ButtonClick);
in the Page_Load and then grab it in the click event:
switch (((System.Web.UI.WebControls.ImageButton)sender).CommandName)
...
but because there are new rows being added and deleted, this gets rather ugly programmatically. I'm thinking there must be an elegant solution to dynamic imagebutton creation and retrieval on the fly from server side code. I've done a lot of digging but this one is stumping me.
Thanks in advance...
If you're creating dynamic controls during the event handling phase of the Page lifecycle (for example, in the item selected event), then the control will be gone on the next postback.
In order for dynamic controls to be registered with ViewState, they have to be created in the Init phase of the event lifecycle.
Also, you say you're iterating through the Form's controls... when you are adding the imagebutton to the table's cells. Are you recursively descending the control heirarchy to look for the imagebutton?
i've populated a dropdownlist control with different text properties but each text properties had THE SAME value (text property was A, value properties is blah,text property was B, value properties is blahblah, etc... )
ASP.net only checks value properties on postback and because ALL values were the same (for
testing reason) this little annoying behavior happened. Is there a work around? does this mean you can't never have the value to be the same?
Sounds like you are working on the wrong event. Try SelectedIndexChanged.
Ensure you also have the AutoPostBack property set to True.
Resolved
OK, so I got digging on this since I was curious :)
There is a "problem" when databinding with non-unique values.
So, firstly, I publicly apologise for saying otherwise.
To replicate:
ASPX
<asp:DropDownList ID="myDDL" runat="server" AutoPostBack="True">
</asp:DropDownList>
<asp:Label ID="lblSelItem" runat="server"Text="Currently Selected Item: 0"></asp:Label>
<asp:Label ID="lblSelVal" runat="server" Text="Currently Selected Value: X"></asp:Label>
Code-Behind
List<string> MyData()
{
List<string> rtn = new List<string>();
rtn.Add("I am the same value!");
rtn.Add("I am the same value!");
rtn.Add("I am the same value!");
rtn.Add("I am the same value!2");
return rtn;
}
protected void Page_Init()
{
if (!Page.IsPostBack)
{
// Load the Data for the DDL.
myDDL.DataSource = MyData();
myDDL.DataBind();
}
}
protected void Page_Load(object sender, EventArgs e)
{
// Display the Currently Selected Item/Value.
lblSelItem.Text = "Currently Selected Item: " + myDDL.SelectedIndex.ToString();
lblSelVal.Text = "Currently Selected Value: " + myDDL.SelectedValue;
}
Run, changing the values in the DropDownList. Note that a PostBack does not occur.
When looking at the Source, I realised that we need to explicitly set the "value" attribute for the <option> elements generated by the server control, which lead me to do something like:
New Code-Behind
Dictionary<string, string> MyTwoColData()
{
Dictionary<string, string> rtn = new Dictionary<string, string>();
rtn.Add("1", "I am the same value!");
rtn.Add("2", "I am the same value!");
rtn.Add("3", "I am the same value!");
return rtn;
}
protected void Page_Init()
{
if (!Page.IsPostBack)
{
// Load the Data for the DDL.
Dictionary<string, string> data = MyTwoColData();
foreach (KeyValuePair<string, string> pair in MyTwoColData())
{
myDDL.Items.Add(new ListItem(pair.Value, pair.Key));
}
myDDL.DataBind();
}
}
This explcitly sets the values to the "1", "2", "3" etc making them unique, while still displaying the correct data within the list.
Obviously, you can change this to work with single-column lists but just running through a for loop and using the value of i or something.
As to good workarounds with DataSets, not sure.
Realistically, would we present a list of options with the exact same values to the user?
I personally think not, which is probably why this "problem" hasn't been addressed :)
Enjoy!
PS:
Oh, I should also add, if you want to use the text value in the "fix" then change it to SelectedItem rather than SelectedValue.
ASP.NET can't distinguish between different items with the same values in the dropdown because when the browser sends the HTTP POST, it sends just the selected value.
ASP.NET will find the FIRST item in the dropdown with a value that matches.
You need to ensure that each item in the dropdown has a distinct value. You could do this by adding a key to each value. In other words, instead of having "blah" for each value, you'd use "blah-1", "blah-2", etc.
The problem is that if the selected index doesn't change the postback won't fire. In the case where the user makes the same selection, the selected index does not change.
Sorry that this doesn't answer the question, but it does explain the behavior as far as I know.
The SelectedIndexChanged won't even trigger because all the listitem value in the dropdownlist control are the same. I did some googling. It seem like this is the common problem. I haven't found any work around yet.
You could use values like this:
1:2
2:2
3:2
Where the second number is the "real" value. Then your event should fire and you can parse out the "real" value in your code behind.
Why do you have a drop down where all of the values are the same? Or is just that some of them are the same?
If you think back to pre ASP.Net days then the only thing that is send with a form submit from a <SELECT> is the VALUE of the <OPTION>. ASP.Net then effectively works out which item is selected by looking up this value in the list of data items.
You will also notice that if you have two items with the same value but different labels that if you do trigger a postback the next time the form loads the first one will be displayed, even if you have the second one selected before you performed the postback.
If you take a step back for a moment and consider your original data source - how would you identify which text value was selected if all you have is the Value? How would you select that value from a database, or from a list? How would you update that row in the database? If you try it you will find that .Net throw an Exception because it cannot uniquely identify the row.
Therefore you need to add a unique key to your data.
I'm trying to set the value of a hiddenfield control in an AJAX initialize request handler. However on the server the hidden field control always contains the value for the previous postback. I presume the viewstate is being prepared / send before I set the hidden field in the initialize request handler.
Is there any way to set the hidden field so that is passes the new value through or perhaps pass a value to the server via another mechanism.
This is the code I'm using:
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(MyPage_initializeRequestHandler);
function MyPage_initializeRequestHandler(sender, args)
{
var hiddenField1= $get('hiddenField1');
if (hiddenField1 != null)
{
hiddenField1.value = 'test';
}
}
Many thanks.
Are you using update panels?
If you are then you need to make sure that the hidden field is inside the update panel that is being refreshed, otherwise the new value will not be sent to the browser.
Also, how are you creating the hidden field, if it's part of an update panel post back you should be using ScriptManager.RegisterHiddenField.
HTH's