I've been looking for a reason why this doesn't work, but I can't find one. In my asp.net application I create a a bunch of hidden inputs in c# and then try to modify them in javascript before I call them back to the server.
My c# code:
hidden3 = new HtmlInputHidden();
hidden3.ID = "total";
hidden3.Value = index.ToString();
this.Controls.Add(hidden3);
my javascript code:
mod = document.getElementById("total");
mod.value = newVal;
I can call the value back fine but it doesn't change. I have also added alerts for the original value and then the value after changing values and they both show up fine. However the code is never changed so when I pull the values
To get the value back I am using this;
HtmlInputHidden hiddenControl = (HtmlInputHidden)FindControl("total");
Have you verified that the resulting input tag as the ID of "total"? By default, in Webforms, the actual client-side ID is prefixed with the parent's Id (and a delimiting character); this helps to ensure that IDs are unique. One way to get the real client-side Id is to pull the value from the ClientID property of the control, but you should only look at that value once it has been put in a Controls collection.
These controls are dynamically created and they have to be created in each postback. However, these should be built before Page_Load preferably in Page_Init event handler. If these are created in Page_Load, the view state has already been processed and the control can't be set from the posted value.
Related
I have an aspx page of images that, when selected, a popup appears prompting for various information tid bits that I then store the information as data attributes on hidden labels through use of jQuery (i.e. data-id="####", data-difficulty="###", etc.). I acknowledge that this isn't the best way to do it necessarily but I've tried other things (see below) and nothing has worked yet.
I've been attempting, and to no avail, to retrieve the dynamically updated data attributes so the various items can be stored to my local ms sql database. The updating of the attributes works perfectly in that I can view the items being updated properly in Chrome's developer tools. Despite this when I try to pull the same attributes I can see as being updated I'm unable to retrieve the updated values in the code behind and keep getting back the initial values (generally an empty string "").
Here's the implementation on the aspx page:
<asp:Label runat="server" ID="lblSelection" data-id="" data-count="" data-price="" data-difficulty="" CssClass="selected-items" />
and here's the relevant method being called when the "Submit" button is clicked further down on the same page:
protected void SubmitClicked(object sender, EventArgs e)
{
var currentID = lblSelection.Attributes["data-id"];
var currentCount = lblSelection.Attributes["data-count"];
var currentPrice = lblSelection.Attributes["data-price"];
var currentDifficulty = lblSelection.Attributes["data-difficulty"];
if (currentID == null || currentID == "")
{
// stop and throw an informative message to the user
}else{
// keep processing ...
}
}
The trouble is that when I run the project in debug mode and inspect those elements (again, making sure that I can visually see that the attributes are actually updated in the developer tools) they're all the initial value of "". My only guess is that there's some kind of post back issue but I wouldn't think that would happen until my method had been called and fully processed. As a note, I'm populating the images onto the page and updating their attributes already through a sql call based on the id of the item:
<img runat="server" src="" data-id="12345" />
The initial loading all works perfectly so I can clearly set the properties from the code behind fine. For whatever reason though I am unable to pick up the updated attribute values in the code behind after the jQuery updates the label's attributes (following some clicking and whatnot). Any tips or thoughts on this would be greatly appreciated.
What you are trying to do cannot work because:
The value of custom attributes is not posted back to the server (as discussed here).
Even if you set the text of the Label in client code, it would also not be available in the Text property in code-behind. A Label is rendered as a span element in the page, and the content of that type of element is not posted back to the server.
A nice list of properties included in a postback is given in this topic: Which values browser collects as a postback data?
As suggested by mshsayem, you should use HiddenFields. If, for some reason, you want to do it differently, you could use hidden TextBoxes, set their value in client code, and retrieve it with the Text property in code-behind. In other words: HiddenFields are not the only controls for which a value set in client-code can be retrieved in code-behind (but they are the obvious choice if the control is not to be displayed).
I know there's a lot of information on this, but mine doesn't seem to be working out so well. I have a form that's created in C# in a form panel. My textfields are created like below:
Ext.Net.Panel panel = new Ext.Net.Panel();
Field field = null;
field = new TextField();
field.Name = "FieldTitle";
field.ID = "FieldID";
panel.Add(field);
this.searchform.Add(panel);
this.searchform.Add(new Ext.Net.Button()
{
Text = "Search",
Handler = "getID();"
});
When the search button is hit, then a JavaScript function is called which performs a store reload:
Ext.getCmp("#Gridpanel").getStore().reload({});
On the reload, I want to read the form fields and use the text for another part of the code. However, the below code doesn't seem to be working:
if(X.isAjaxRequest){
var ctrl = X.GetCmp<TextField>("FieldID");
string value = ctrl.Value.ToString();
}
I can get inside the 'if' statement, but ctrl comes back as null. Is there something else I need to include to grab the text field data?
EDIT
So I'm realizing that I'll have to pass an array of the search field ID's to a JavaScript function, then send a dataset back to the server side in order to implement the search. Just to throw it out there, is there a way to dynamically create controls (ie; a TextField) in C# and then get the value from those controls after an event is fired (ie; a button click)?
You can try to get the textfield using
Ext.getCmp("#FieldID") or X.getCmp("#FieldID"). FieldID is the client ID for TextField.
Use developer Tools to check the ID for the TextField
I'm writing code to read data from asp controls to update records in a database. I've been debugging the last day and I've tracked it back to something that I ought to have noticed before.
The code first populates the controls with the existing values from the database.
When I click SAVE, it should read the current values from the controls and save with those.
Unfortunately, what it's actually doing is using the values of the controls before a change was made to them. It's not seeing the change to the controls.
Here's a sample:
<asp:TextBox ID="OtherCourseName_5" runat="server"></asp:TextBox>
Here's the corresponding behind code in the btnSave_onClick() function:
int object_number=5;
string other_course_name_string
= "OtherCourseName_" + object_number.ToString().Trim();
TextBox ocn = utilities
.utils
.FindControlRecursive(this.Master, other_course_name_string) as TextBox;
I'm using the FindControlRecursive() I found somewhere on the web. It works, I'm sure, but just in case, I tried to address the control directly as OtherCourseName_5.Text.
Even if I just display the value in OtherCourseName_5.Text, it gives the original value.
I use this same page for both entering new data and for editing data. It works fine when I enter the data. That is, it correctly sees that the TextBox control has changed from empty to having data. It's only when I invoke the edit function on the page (by passing edit=true). I invoke it this way by adding the switch edit=true as a query string (the program correctly reads that switch, gets to the appropriate area of code, prints out all the correct values for everything - except the contents of the controls!).
The page is far too complicated to post the entire thing. I've tried to convey the essential details. It's entirely possible that I've made a simple coding error, but it's seeming more a possibility that I fundamentally misunderstand how pages are processed.
Is there anything known that can make it seem as though the value of a control has not been changed?
Note 1: I thought perhaps I had to go to another field after I entered the data, but I tried that and it's still a problem.
Note 2: I'm using both TextBox and DropDownList controls and have the same problem with both.
Note 3: These controls are on a panel and the page is using a SiteMaster. I haven't had any problem with that and don't think the problem is there, but I'm down to questioning the laws of the physics at this point.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//populate controls with data from database
}
}
When you do a postback before the postback handler is evaluated the PageLoad event is raised
so if you don't avoid to rebind your control they will be loaded with the values from the database. And then the postback event will save them to db
Asp.net Page Lifecycle
(source: microsoft.com)
I would like to read the Form value of a control (e.g TextBox), i.e 'Request.Form["[Control_Name_Here]"]. The problem with using say TextBox.Text is because if you explicity set it yourself in the Page_Load, there is no way you can get back the 'original value' submitted in the form.
As you know, Asp.Net generates a unique ID/Name for the control. The Request.Form is based on the name attribute of a control. Each webcontrol has a ClientID property, however this does not match the name. The name seems to be almost like the ClientID, having $ instead of _. Is there a way to easily get the value from the form, without resorting to having to replace the _ to a $?
And this should also cater for other naming-conventions, because as from Asp.Net you can also choose to have a control's id statically-generated, rather than dynamically.
It sounds to me like you're not looking for the .ClientID property, but the .UniqueID property of the Control.
See: MSDN
Edit: Also, is there a reason you're always setting the .Text property within the page load? Instead of for example check the Page.IsPostBack property instead and only set the .Text if it's false?
I personally use jquery to find the control and read and set the value
GetFormValue = function (idName) {
var srchP = '[id='+idName+']';
var ctrl = $(srchP);
if (ctrl != null)
return ctrl.val();
return null;
}
so assume th id name in server part is txMytext
and it will be .....$txMytext in client
and by calling GetFormValue('txMytext') in client side you cna get the value of control
dont foget to use jquery library
I have read a ton about this problem, but I cannot figure it out.
I have a dropdownlist on my view that is used for paging. You choose the page you want to go to and the form gets submitted. When the view is returned, the requested page is shown. The dropdownlist changes to reflect the newly shown page. This is working fine.
My problem is this:
I have 2 submit buttons, one for next page and one for prev page.
In the controller, if one of the submits have been pressed, the page# should be incremented or decremented by 1. This is happening, and the correct page of data is being shown. But, the dropdown list will not, NO MATTER WHAT I DO, reflect the new page number when the view is shown.
Basically, if the dropdown is changed by the user, it will reflect those changes when it is sent back after a form submission. If I change the page # programmatically, the dropdown will not change, even though the correct page of data gets shown.
Here is the action method:
public ActionResult Results(TechSearch search, string NextPage, string PrevPage)
{
if (NextPage != null) search.Page++;
if (PrevPage != null) search.Page--;
int resultCount = search.GetResultCount(Desk);
List<int> pages = new List<int>();
int pageCount = (int)Math.Ceiling((decimal)resultCount / search.PageSize);
for (int i = 1; i <= pageCount; i++) pages.Add(i);
ViewData["pages"] = new SelectList(pages, search.Page);
ViewData["pageCount"] = pageCount;
return View(search);
}
And here is the relevant part of the view:
<input type="submit" value="<" name="PrevPage" />
Page
<%=Html.DropDownList("Page",(SelectList)ViewData["pages"]) %>
of
<%=ViewData["pageCount"]%>
<input type="submit" value=">" name="NextPage" />
Please help.
EDIT
Page 333 of Pro ASP.NET MVC Framework by Steven Sanderson:
How Input Controls Get Their Values
Each of [the HTML Helpers for Rendering Input Controls] tries to
populate itself by looking for a value
in the following places, in this order
of priority:
ViewData.ModelState["controlName"].Value.RawValue
value parameter passed to HTML helper method, or if you’ve called an
overload that doesn’t include a value
parameter, then
ViewData.Eval("controlName")
ModelState is a temporary storage area
that ASP.NET MVC uses to retain
incoming attempted values plus binding
and validation errors. Notice that
it’s at the top of the priority list,
so its values override anything you
might set explicitly. This convention
means that you can pass an explicit
value parameter to act as the helper’s
default or initial value; but when
rerendering the view after a
validation failure, the helper will
retain any user-entered value in
preference to that default.
I have verified that ViewData.ModelState["Page"].Value.RawValue does contain the unexpected page number that is pestering me. What's the best way to work around this?
The problem was that ModelState was holding the dropdownlist's passed in value. For the HtmlHelper input controls, ModelState is given priority over explicitly set values when displaying a value in the input control.
Here is what I have done in my action method to fix the problem:
ModelState.Remove("Page");
return View(search);
I am interested in hearing other ways of fixing my problem.
Change the selected value with javascript on the click of the next or previous button, right before your postback.
Are you sure that you are guaranteed that at least one of NextPage or PrevPage will be null? (And you don't get anything weird like String.Empty forcing an increment and decrement?)
Could .LastOrDefault() be replaced with just .Last() and you are sure that you are not assigning default(int) to search.Page?
Does the below have any effect?
ViewData["pages"] = new SelectList(pages,
pages.FirstOrDefault(p => p == search.Page ));
Replacing
ViewData["pages"] = new SelectList(pages, search.Page);