I'm using Visual Studio 2015 - ASP DOTNET C# and WebForms
I've written a program and part of it requires the user to input a number via a textbox, when the user tabs out the event fires successfully and retrieves the record populating all relevant fields on the form.
Sometimes the user can input another number and it fires, on occasion the textbox locks up as if the read only is true, it won't allow you to delete the text, input further text etc, you have to click a random button on the page which then clears the issue. I'm pretty stumped as to why it's doing this.
protected void txtAsset_TextChanged(object sender, EventArgs e)
{
//Validate text input
lblSuccessful.Text = string.Empty;
txtAsset.Focus();
string input = txtAsset.Text;
if (!Regex.IsMatch(input, #"^[0-9]\d*"))
{
lblSuccessful.CssClass = "ErrorMessage";
lblSuccessful.Text = "You have input invalid criteria";
txtAsset.Text = string.Empty;
txtAsset.Focus();
}
else
{
Execute Retrieval of record code
}
}
Many thanks for your help
Because of PostBack in asp.net WebForms.
You have two options:
Check validation in client side with jquery.
put your controllers in UpdatePanel.
Related
I'm working in Visual Studios to create a website for a movie theater (for class) I'm wondering if there's a way to "remember" what link is clicked for a show time? I know I could just create a webpage for each time, but I'd rather track an id, if that's possible!
By clicking the link, they'll go to the right page, but is there any way for me to put into the system what time they clicked? I couldn't find any similar questions here.
you could use sessions to hold the showtime selected. create an LinkButton with an onCommand that creates a session before redirecting them to the seating chart or checkout page.
so say a user is on your movie page and the user selects the 12pm showtime. When the user clicks on the link, it will run what ever is in your code behind. You can create a Session["DateTime"] and set it to the value of the linkbutton. then, redirect to the seating page.
on the seating page, you can check if there's a session. if it finds one, then you can load the seating chart or purchasing page. if it does not find one, you might want to redirect them back to select a time.
HTML example:
<h2>Next Big Movie</h2>
<asp:LinkButton id="lbNBM12pm" runat="server" OnCommand="lb_Click" text="12:00pm"></asp:LinkButton>
Code Behind example:
protected void lb_Click(object sender, EventArgs e)
{
string time = (sender as LinkButton).Text;
Session["TimeSelected"] = time;
Response.Redirect("/nextstep.aspx");
}
and on the next page, you'll read what was passed over in the page load and set the Selected Movie time text:
protected void Page_Load(object sender, EventArgs e)
{
if(Session["TimeSelected"] != null)
{
MovieTime.Text = Session["TimeSelected"].ToString();
}
else
{
//user did not select a time
//possibly redirect them back to the showtimes page.
response.redirect("/previousepage.aspx");
}
}
If I understand it correctly. First, create a table with the following columns:
create table Links
(
id int identity,
link varchar(100),
timeclicked datetime
)
then fire an ajax or a simple HTML POST request to submit what link is clicked in a spefic time.
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
I am trying to create a program in C# (maybe using WinForms) which will enter a licence number into a form field of a specific website and validate whether or not the licence number is a currently valid licence.
I am unsure as to where to start, as I can't even find the form field id in the source code of the website, and am unsure what technologies the website uses.
Additionally, the purpose of this program will be to enter a list of license numbers and return the names and validation status of each license. Datasource being the website.
Any information on how to go about this would be much appreciated, I am an intermediate C# developer - having mostly worked in ASP.Net, though feel Winforms may be better suited for this project.
Kind Regards
You can use a WebBrowser control:
You can load the page using webBrowser1.Navigate("url of site")
Find elements in page using webBrowser1.Document.GetElementById("buttonid") also you can iterate over HtmlElement of webBrowser1.Document.Body.All and check for example element.GetAttribute("value") == "some vaule" to find it.
Set value for element using element.InnerText ="some value" or element.SetAttribute("value", "some value")
Submit your form by invoking the submit of form or click of its submit button using element.InvokeMember("method")
Example
For example, if you browse google and look at page source, you will see name of search text box is "q" and name of the form that contains the search box is "f", so you can write this codes to automate search.
Create a form with name BrowserSample.
From toolbox, drag a WebBrowser and drop on form.
Hanfdle Load event of form and navigate to google.
Handle DocumentCompleted event of webBrowser1 and find f and find q and set InnerText of q and invoke submit of f. This event fires after the navigation and document load completed.
In a real application add required null checking.
Code:
private void BrowserSample_Load(object sender, EventArgs e)
{
this.webBrowser1.Navigate("https://www.google.com/");
}
void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
//Because submitting f causes navigation
//to pervent a loop, we check the url of navigation
//and if it's different from google url, return
if (e.Url.AbsoluteUri != "https://www.google.com/")
return;
var f = this.webBrowser1.Document.Body.All.GetElementsByName("f")
.Cast<HtmlElement>()
.FirstOrDefault();
var q = f.All.GetElementsByName("q")
.Cast<HtmlElement>()
.FirstOrDefault();
q.InnerText = "C# Webbrowser Control";
f.InvokeMember("submit");
}
If you execute the program, it first navigate to google and then shows search result:
In your special case
Since the site loads content using ajax, then you should make a delay in DocumentCompleted:
async void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (e.Url.AbsoluteUri != "https://www.onegov.nsw.gov.au/PublicRegister/#/publicregister/search/Security")
return;
await Task.Delay(5000);
var f = this.webBrowser1.Document.Body.All.GetElementsByName("searchForm")
.Cast<HtmlElement>()
.FirstOrDefault();
var q = f.All.GetElementsByName("searchText")
.Cast<HtmlElement>()
.FirstOrDefault();
q.InnerText = "123456789";
f.InvokeMember("submit");
}
Don't forget to add using System.Threading.Tasks; or if you use .Net 4.0 you simple can use System.Threading.Thread.Sleep(5000) and remove async/await.
It looks like the website uses JSON POSTs. If you have FireFox open Developer -> Network and look at the "PerformSearch" entry. That will tell you everything you need to know as far as what the website is expecting in a POST request so you can read the response.
I've created a form to send message for admin, and when I click on send button all things are fine and data are sent and saved to the database and I print success message. But if I refresh the page -by pressing F5- the message is sent again to the server and database!. How can I fix this problem ?
I just want to send message to the server once when I click on send button, not on refresh page.
my code is
<asp:Button ID="btnsenddata" runat="server" OnClientClick="return validate()" OnClick="btnsenddata_Click" Text="SendData" />
protected void btnsenddata_Click(object sender, EventArgs e)
{
//this place i connect to DB
}
This is a commond issue. The behavior is by design: The information of the
button that was pressed is actually re-sent to the server (along with all
other information of the controls) when the page is being refreshed.
A nice way of workaround i found, while surfing the net, is (this way is on the server side) to use HashTable:
//Class member
HashTable ht = new HashTable();
btnMyButton_Click(object sender, EventArgs e)
{
ht =(Hashtable)Application["UserOKHashtable"]
if ((ht.ContainsKey(Session["UserSessionKey"]))
{
// double - clicked or user pressed refresh
return;
}
else
{
(ht.Add(Session["UserSessionKey"],UserName);
// your code here
// and finally
((Hashtable)Application["UserOKHashtable"])
.Remove(Session["UserSessionKey"]);
}
}
Remember to remove the user's session key from the hashtable at the end
of the procedure, otherwise the user will only be able to click the
button once during the whole session.
If you search for "prevent double post", you will find more information and possible workaround for it.
hope it'll help :)
I would put a OnClick handler on the button. So, in your .asp file <asp:Button id="btnMyButton" runat="server" OnClick="btnMyButton_Click"
Then on the aspx.cs side you add method 'btnMyButton_Click' and put your code in there
btnMyButton_Click(object sender, EventArgs e)
{
//your code to update database goes here
}
You will have to come up with some method, probably in the database, to ensure that repeated messages are not sent within a certain period of time. You can't easily get around the F5 issue because all that does is tell the browser to repeat exactly what it did the last time. This means the same data is sent to the user. That is the trick, any check you put in must store the data within the server since the client will just replay the last action.
You could hold a session variable to let you know when the user sent this form last (just ensure you check for Session["sentform"] != null when checking for the session variable)
Also, you could create a simple log in the database to say what user clicked (if you have logged in users), the time it was last sent, and something that will let you identify which page, message requestor was fired. Then you can ask the database if this user has sent message for page/process X within the last couple minutes and return true or false.
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;
}
}