ASP.NET - Controls submit wrong information - c#

in ASP.NET I have 2 text boxes, one dropdownlist and a button that submit the wrong information to a method that I am calling.
I am using Linq to SQL with Entity Framework.
What I am trying to do is updating a ticket in the database that contains a subject, content and isPublic(bool). When I load the page it automatically fills the text boxes and combo boxes with the fields from ticket where the ticket id is known. So if ticket 2 is clicked,the page loads and the controls get filled with the information from that ticket. So if ticket 2 has a subject Dogs, content a Dog is an animal and isPublic is true, you'll get to see that information in those boxes. Now, when I change the content of those controls and press the button, it loads a method that I wrote to update the database:
public void updateTicket(int _ticket_id,bool _isManager,string _subject,bool _isPublic,string _description)
{
TICKET ticket = (from t in db.TICKETs
where t.id == _ticket_id
select t).First();
REACTION reaction = (from i in db.REACTIONs
where i.tickets_id == _ticket_id
select i).FirstOrDefault();
ticket.subject = _subject;
ticket.isPublic = _isPublic;
reaction.contents = _description;
db.SubmitChanges();
}
And I call this function like this:
instanceOfTickets.updateTicket(2, false, TextBox1.Text,waarde,TextBox2.Text);
Where ticket_id is 2 just for testing and waarde is Public.
The problem that I have is when I debug this method, the controls return the wrong information to the method overload. Instead for example cat, it still sends dog to my method. Even though I really filled in cat before clicking the button.
Does anyone know why it does this and how to fix this?
Thanks in advance.
EDIT:
To be more clear:
After loading the page:
Here I changed the content:
After I pressed the button and started to debug:
EDIT 2:
So I figured out what causes the problem but I don't know how to fix it. I have a var ticket that contains the ticket after I used a linq query to get that ticket from the database. When I tell a text box to get fill itself with the subject (or content) from that ticket, it keeps somehow "connected" to that. So when I say textbox1.text = ticket.subject , the subject will show up in that text box but it will always stay like that. How do I "overwrite" that so that I can send the proper information to my method?

Looks like you fill your data on every postback in Page_Load without checking Page.IsPostBack. So after you submit your form it primarily fills textboxes from db and after that it tries to update data. But textboxes already contain original values from DB.
small example of initial data set
public void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var myObj = GetdataFromDb();
TextBox1.Text = myObj.Subject;
TextBox2.Text = myObj.Desctiption;
}
}

Related

Losing values after refreshing button asp.net

I have the following project :
It's a page that on Page_Load it fills a TextBox named Email and a TextBox named UserName with a value obtained from asking a database.
Then there is this button, if the email is not null(user is not registered) it will let you register, otherwise it will let you change the email linked to your username.
The thing is, when trying to modify the email, doing an update query, the page preloads, taking the new value placed on Textbox Email the same that is retrieved from the database, making so it will never change.
I've tried to see if it executes the query and it does.
I've tried everything, keeping the variable on a hidden label, creating two different buttons with no luck as when it reloads the code those values are empty again.
I was thinking if I could keep the variable somehow that isn't cookies.
I think You know What is happening.. On every Post back the Page_Load event resetting your Textbox Value
Use IsPostBack to bind the value only on 1st load of page
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//bind dropdown and fill textbox here
TxtName.Text = "Your values";
GetDropdowns();
}
}
I hope this will solve your issue
I totally agree with Kanis XXX, you can use IsPostBack to fill the values only at the start page, and not on other postbacks. In my experience, there are some other advices for your problems:
Using Viewstate, Session state,... to keep your working variable. You can have more detail here: https://kimphuc.wordpress.com/2009/10/18/the-difference-between-viewstate-sessionstate-cookies-and-cache-in-asp-net/
Try to use UpdatePanel, this could be useful in some cases, let you refresh or update data just a part of your page, not the whole page. https://msdn.microsoft.com/en-gb/library/bb398864%28v=vs.100%29.aspx

How can I grab a textfield value in Ext.Net?

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

Manage form data on click of asp.net back button (other than handling though Session or Viewstate)

I have a form on search page having textboxes, dropdowns, checkboxes. After selection of Search Criteria and clicking on Search button search results displays on another page. I am using a asp button on search result page to go back to search page and I want to retain the form data (textboxes, selection of dropdowns/checkboxes etc. which I have made earlier for search). I have implemented it through Session and Viewstate so I want to know some other way to manage this.
Many Thanks for you replies,
Harish Bhatt
There are many things You can do.
1.Cross Page Scripting
One of the problems faced by us in ASP.NET 1.x versions is the inability to transfer data between pages easily. Since ASP.NET 1.x pages postback to the same page by default, and you cannot do a post to another page (unless you remove the runat="server" and other messy things), accessing the controls in the previous page becomes very difficult unlike classic ASP where you have a action tag to specify the new page and you can use the Request.Form to access the previous page values.
There is a more effective way of accessing the Controls in the previous page in ASP.NET 2.0. Its using the PreviousPage property of the Page.
Say we have a page Default.aspx with a Textbox "Text1" and a Button "Button1".
We can access the controls in Default.aspx from another page by the following steps:-
A. Setting the PostBackUrl property of the Button to the New Page, as follows:-
<asp:Button ID="button1" Runat=server Text="submit" PostBackUrl="~/NewPage.aspx" />
B. Then, in the NewPage.aspx.cs, you can access the TextBox control on Default.aspx as follows:-
public void page_load()
{
if(!IsPostBack)
{
TextBox tb = (TextBox)PreviousPage.FindControl("Text1");
Response.Write(tb.Text);}
}
Note that a new TextBox tb is declared and typecasted using the PreviousPage and FindControl of the ID of the Control in the Previous Page. However, to retain the value across postbacks within the new page, its better to assign the text to a TextBox or Label in the NewPage.aspx such that its value is not lost across postbacks. The reason behind is that, the PreviousPage becomes invalid once you postback in the same page.
2.Sessions
You can refer the below link for help
http://asp.net-tutorials.com/state/sessions/
example
Session["Value"]="Any Data";
You can access it in any page
3.Cookies
Creating a Cookie Object
HttpCookie _userInfoCookies = new HttpCookie("UserInfo");
Setting values inside it
_userInfoCookies["UserName"] = "Abhijit";
_userInfoCookies["UserColor"] = "Red";
_userInfoCookies["Expire"] = "5 Days";
//Adding cookies to current web response
Response.Cookies.Add(_userInfoCookies);
You can use a query string that holds the IDs of the selected items in textbox, dropdown, check box, etc., like this:
Search.aspx?textId=3&dropdownId=7
You would also need to pass these values to your results page, so they can be passed back to the search page when you want to get back.
Results.aspx?textId=3&dropdownId=7
Note: This alternative becomes unwieldy as the number of parameters increases, but it is a viable alternative to Session cache.
I recommend storing clientstate information in a the database -- they are occasionally useful that way! You can define the corresponding rows and columns to represent the state info you need to track or just put all of your state info into a persisted stream (using json, xml etc.) as long as your don't to to search or perform db operations on the streamed values. Putting this in a database makes it easy to migrate to a web farm, or add failover, etc. The clientstate database database does not have to be the same database as the rest of your application for more scalability. If you are using sessionstate, you can also configurate asp.net to keep session state in a database to accomplish the same thing. Personally I store the heavily used clientstates in custom table, and use the general streamed method for lower volume clientstate info.
The trick is to use the sessionid as the key (or the sessionid + XKEY) where XKEY is needed if you need to store multiple copies of state info in the same table. e.g., on a storefront app XKEY might represent page # or suchlike. I also use this to generate a unique XKEY and pass the XKEY in the uri query parameterlist -- you only have to persist XKEY from page to page, not a long list of parameters.
I have already described the situation above here I was trying to maintain the Form data of search page on click of Back button from search result page, details page and other pages. To maintain this I used the Class SearchCriteria. Below is the sample code for Class
public class SearchCriteria
{
private string _strName;
private string _strCode;
public string strName
{
set { _strName = value; }
get { return _strName; }
}
public string strCode
{
set { _strCode = value; }
get { return _strCode; }
}
}
I have assigned all Search Criteria to this class and kept that in Session so that I can access this anywhere.
SearchCriteria objSearch = new SearchCriteria();
objSearch.strName = txtFirstName.Text;
objSearch.strCode = txtCode.Text ;
if (Session["SearchCriteria"] != null)
{
Session.Remove("SearchCriteria");
Session["SearchCriteria"] = objSearch;
}
else
{
Session["SearchCriteria"] = objSearch;
}
One Click of Back button from search result, details and other pages I am redirecting to Search Page with the QueryString PostBack=1
protected void btnBack_Click(object sender, EventArgs e)
{
Response.Redirect("Default.aspx?PostBack=1", false);
}
And on the Page_Load of Search page I checked for the 'QueryString' PostBack and based on the QueryString, I have assigned the Search Criteria to the Controls from Session.
if (Request.QueryString["PostBack"] != null)
{
SearchCriteria objSearch = new SearchCriteria();
if (Session["SearchCriteria"] != null)
{
objSearch = (SearchCriteria)Session["SearchCriteria"];
txtFirstName.Text = objSearch.strName;
txtCode.Text = objSearch.strCode;
}
}
I don't know what is recommended for different situations but like to know. Please share your ideas.
Many Thanks to Ashish Bahu, his answer helped me a lot on this.
I was looking for any other good way to do this without using Session or Viewstate but didn't found anything and finally end up with the above solution, If someone is having any other good solution for this please share. Thanks!

Javascript added input control on .net postback

What I'm trying to achieve/plan, is whereby a page loads with a set of inputs, e.g. TextBox, Radio List etc. Taking TextBox as an example, there is a button for the user to "Add" another textbox to the page (in the same group), e.g. Member1, Member2, Member3 etc etc.
Two questions:
I could add these with Javascript, however the resultant "save" on postback would not get these inputs? If so, how?
The form needs to work without Javascript as well, so postback to dad another control is fine, however if I click the "add" button again, it will only ever add one control.
protected void btnAdd_OnClick(object sender, EventArgs e)
{
holder.Controls.Add(new TextBox { ID = "txtControl1" });
}
You can access the dynamic controls in the postback by name, using the following syntax "Page.Request.Form[""].ToString();". This uses the "name" attribute, not the "id" attribute.
I guess you can have one of these scenarios :
1- to save any new control ( textbox ) data in a session variable .. for example save name and value in which when any post back you can draw then again from this variable
2- If the only post back done from Add button you can do its function without doing post back as in this example http://msdn.microsoft.com/en-us/library/ms178210.aspx

C# .Net variable unexpected re-initialation

So I am experiencing an issue with an .aspx page and some server side code, where I am getting unexpected results.
The goal of this page is simple, there are 5 radio buttons and a button with a server side onclick function. The idea is the user picks 1 of the 5 radio buttons, and then clicks the button. Upon clicking the button I verify (not using form validation, because I wanted a different feel) that a button is checked, and then store the selected option in a database.
Due to the fact that the number of radio buttons may change in the future I decided to try and abstract the number of radio buttons to make it easier on my self to change in the future.
So at the top of my server side code I created a list of possible options.
I then have a registerVote function that takes in a RadioButton object, and a number to grab a setting from the config file. I throw those 2 values into a wrapper class, and then add them to the list of possible options.
Finally when the submit button is pressed, I iterate through all possible options to see which one is checked, and grab its associated value.
public partial class VotePanel : System.Web.UI.Page
{
List<VoteOption> voteOptions = new List<VoteOption>();
public string registerVote(RadioButton newRadioButton, int voteOption)
{
voteOptions.Add(new VoteOption(newRadioButton, voteOption));
return ConfigurationManager.AppSettings["vote_option_" + voteOption];
}
protected void Submit_Click(object sender, EventArgs e)
{
//Check vote
string vote_value = "";
bool someButtonChecked = false;
foreach (VoteOption vo in voteOptions)
{
if (!someButtonChecked && vo.button.Checked)
{
vote_value = vo.movie;
someButtonChecked = true;
}
}
//....
}
}
class VoteOption
{
public RadioButton button;
public int vote_value;
public VoteOption(RadioButton r, int v)
{
button = r;
vote_value= v;
}
}
The code I use in page to add a radio button looks like this
<asp:RadioButton ID="RadioButton1" runat="server" GroupName="Vote" style="position: relative; top: 3px;" /><%=registerMovie(RadioButton1,1)%>
Now for the problem I am experiencing. Whenever the submit button is clicked, the list has a count of zero, and looks like it has been reinitialized. I validated that values are being added, by returning the list count in the registerVote method, and objects are indeed being added, but for some reason are not available to the Submit function.
Now variables on a page like this shouldn't reinitialize right? I also tested a string, and it did not reset and was available to the Submit button. What I did was define a class variable string time = DateTime.Now.Ticks.toString(); and displayed that after the submit button was clicked, and the time was always the same reguardless of how many times I clicked it.
So why would my List reinitialize, but not a string? Any ideas?
Keep in mind that your page class will be constructed and destructed for every request - no state will be maintained between each page load, it is up to you to properly recreate state as needed. In this case it appears that your list voteOptions is not being recreated before Submit_Click is called.
You'll have to register all your voting options regardless of whether the page is in a postback or not inside the Page_Load or OnInit handlers of the page. This will reconstruct voteOptions, which will then be accessed when Submit_Click is called.
Take a look at the ASP.NET Page Life Cycle.
The problem seems to be that you are constructing the List<VoteOption> voteOptions at page render then expecting it to still be there on postback. The Page object does not exist past the point that the page is delivered to the browser, so your list of vote options gets disposed of as well when the browser has received the page.
You'll either need to reconstruct the voteOption list before or during Submit_Click on postback, or give yourself enough information in the value of the radio button that you don't need it.
I don't see in your code any place where the list that you are building is placed in memory. I believe you are rebuilding it on each page reload. P.s. might be my reading but you created a function called registerVote and you are calling a method called registerMovie so that might be your problem.
You could place the list in the session and get it back from session.
Personnally I would change the code to
1) Check if the list is in memory and get it. If not in memory call a method to generate it once and then place it in memory.
2) Use a RadioButtonList on your page that you can then bind to your list as a data source.
asp.net is stateless, so every postback (such as clicking Submit) recreates the server-side class. If you want your list to persist between calls, you should save it in ViewState or a Hidden field. Not sure about the string though; what you're describing doesn't fit the asp.net lifecycle.

Categories

Resources