I am trying to post back on a button click.But unable to get __EVENTTARGET and __EVENTARGUMENT. It is currently always null. Is there any other entries I have to do?
aspx
<asp:Button ID="btn" runat="server" OnClientClick="GetDet();" Text="Click"/>
<script type="text/jscript">
function GetDet() {
var obj = $('.output');
var sign = $('.name'); //hidden field
__doPostBack('btn', sign.val());
}
</script>
.cs
string tar = Convert.ToString(Request.Params.Get("__EVENTTARGET"));
string val = Convert.ToString(Request.Params.Get("__EVENTARGUMENT"));
Instead of doing such a hack. I'd actually recommend you to do things the proper way so you can guarantee scalability because you never know what's gonna happen on the next release of ASP.NET and the ASP.NET Team certainly does not endorse these types of hacks, in other words, your hacks might break with a future releases of ASP.NET...always strive to avoid them. So, if you want to do a full postback you definitely don't need javascript for this....
<asp:Button ID="btn" runat="server" Text="Click"/>
Then, if you want to post the value of the hidden field simply add the hidden field to the form...
<asp:HiddenField ID="hdfName" runat="server" Value="whatever" />
if you want to read the value of the hidden field during the postback...
public override void OnLoad(EventArgs args)
{
var name = hdfName.Value;
}
That's how you are supposed to work with ASP.NET the proper way rather than trying to hack its intrinsics
Related
how do i simply type a value in 1 box and have it populate in another using the asp:textbox. I simply want to pull value from 1 asp:textbox and put it in another, ultimately i am going to be adding the sum of 2 boxes and placing it in another, I would like this to happen in real time and not use a button.
Use javascript:
<asp:TextBox ID="txtTextSource" runat="server" onblur="TextSource_OnBlur(this)" />
<asp:TextBox ID="txtTextDestination" runat="server" />
<script type="text/javascript">
function TextSource_OnBlur(oElement) {
var destination = document.getElementById('<%= txtTextDestination.ClientID %>');
destination.value = oElement.value;
}
</script>
Instead of ASP.net, use jQuery for this since it'll avoid post backs.
hook onto the change event of textbox1 and populate text box 2 using jQuery. Try it and let us know.
I agree with raja, you should use client side JavaScript (doesn't have to be jQuery) to handle this since it doesn't require server interaction. But let's say for some crazy reason you want it to happen on the server.
First Number: <asp:TextBox runat="server" id="TB1" /><br />
Second Number: <asp:TextBox runat="server" id="TB2" /><br />
<asp:Button runat="server" id="CalculateBtn" OnClick="CalculateBtn_Click" Text="Calcualte Sum" />
Sum: <asp:TextBox runat="server" id="SumTB" />
Code Behind
protected void CalculateBtn_Click (object sender, EventArgs e)
{
int num1 = Int32.Parse(TB1.Text);
int num2 = Int32.Parse(TB2.Text);
int sum = num1+num2;
SumTB.Text = sum.ToString();
}
Obviously you can get much more fancy, using doubles instead of ints and verifying that the user typed a valid number and using ScriptMethods or UpdatePanels to do it in real time without the need for a button. But seriously, stick with a client side solution.
$('.amount-input').live('blur', function () {
var amountSum = 0;
$('.amount-input').each(function () {
amountSum += parseInt($(this).val());
});
$('#<%= Damount.ClientID %>').val(amountSum);
enter code here
just used java script and called the total amount which is "Damount" from the server code. Still wish it changed in real time except for when i click off the textbox but hey it works!
I am working on an asp.net 4.0 application. One of the site does is allow users to search for stuff in the database. The page that is done on looks like this:
<asp:Panel ID="pnlSearch" runat="server" DefaultButton="lnkSearch" cssclass="searchbar box">
<span id="searchFor"><strong>Search for</strong></span>
<asp:TextBox ID="txtSearch" runat="server"></asp:TextBox>
<asp:LinkButton ID="lnkSearch" runat="server" Text="Search" onclick="lnkSearch_Click"></asp:LinkButton>
</asp:Panel>
lnkSearch_Click performs the query on the database, then binds the results to a asp:Repeater.
This all works, but there is a problem: The URL is not changed for the user, and so there is no way for the user to save a query for later, or to link to to their friends.
I could solve this by doing something a bit like:
<script>
function doSearch() { location.href='~/defaultpro.aspx?search='+escape($('txtSearch').value);
</script>
<a ID="lnkSearch" href="javascript:void(0);" Text="Search" onclick="doSearch();" />
But this feels like going out of my way to avoid using the tools asp.net provides. Is there a better way to do this?
The best way of doing it is to have a form with method set to get:
<form method="get">
But ASP.NET requires the one huge form that wraps all the controls, so its not an option for you.
Other way you can implement this, is to create an event handler for click event of your Search button:
protected void SearchButton_Click(object sender, EventArgs e){
Response.Redirect(Request.RawUrl + "?search=" + Server.UrlEncode(txtSearch.Text));
}
And bind all the data in the PageLoad event
If you are using .Net 4.0 why are you not using URL Routing?
I wrote this article explaining how to use the new feature.
So you would have a click event that performs your search and then at the end of the search (logic code) you can keep their search in the URL by using URL Routing.
Another method you could use is Sessions. I would not suggest cookies as they are on the client and prone to manipulation. One last option you could use is Context.
If you are going from one page directly to the next you could use page history.
I have a asp file upload for pictures and what I want to do is, when the file chosen has the same name as the previous file it should pop something up that says "This image name already exists, do you want to replace it? if yes then it would just override the current picture with the new one but if not then just leave it alone. How can I do this?. Right now I have this. Also if the solution is in javascript I could also use that (but i am not too good with javascript :) ) Thank you
<div class="style">
Choose an Image: <asp:FileUpload ID="getImage" runat="server" Width="150px" BorderStyle="Inset" EnableViewState="true" />
<asp:RegularExpressionValidator ID="RegularExpressionValidator"
runat="server" ControlToValidate="getImage" CssClass="Error" Display="dynamic" ValidationExpression=".*(\.[Jj][Pp][Gg]|\.[Gg][Ii][Ff]|\.[Jj][Pp][Ee][Gg]|\.[Pp][Nn][Gg])" ErrorMessage="Select a correct file format"></asp:RegularExpressionValidator>
</div>
Please be aware I am a total newbie with Javascript so if that is what's going to work please explain as if I was a 5 year old.
I really appreciate the help.
My solution will perform the check just before postback. I also use jquery a little bit.
The important piece of the puzzle here is retrieving the previous file name. I created a PageMethod to do this part. So in my aspx.cs file I have a function that looks like this:
using System.Web.Services;
.......
[WebMethod()]
public static string GetPreviousFileName()
{
//put logic here to get the filename to compare against.
return "somefilename.ext";
}
You'll need to implement your own logic for how to retrieve the file name. Another, simpler but less flexible, approach for handling the previous file name would be to add an asp:hiddenfield to your page and populate it with the name of the previous file on page load. Then you could compare by reading $('#<%= hiddenField.ClientID %>').val().
Next I used the following code for my file upload control and a submit buton:
<asp:ScriptManager ID="sm" runat="server" EnablePageMethods="true" />
<div>
<asp:FileUpload ID="fu" runat="server" />
<asp:Button ID="btnUpload" runat="server" OnClientClick="return checkDuplicateFile();" Text="Upload File" />
</div>
Two important things to note here: The ScriptManager has EnablePageMethods="true" and the asp:button has an OnClientClick attribute specified. Lastly, the javascript part of the solution which retrieves the value from the page method and and compares the file names:
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
var oFilename = "";
$(function () {
//get original file name on page load
PageMethods.GetPreviousFileName(function (result) {
oFilename = result;
});
});
function checkDuplicateFile() {
var newVal = $('#<%=fu.ClientID %>').val();
var newValFile = newVal.substr(newVal.lastIndexOf("\\") + 1);
//returning true causes postback, returning false stops postback.
if (newValFile == oFilename) { return confirm("This image name already exists, do you want to replace it?"); }
else return true;
}
</script>
Couple of things going on here. We use our pagemethod to pull in our old filename from the page method on page load (PageMethods.GetPreviousFileName). Next we setup the function which will be called by our buttons onClick event (client side). The <%=fu.ClientID %> snippet of code will output the client side id of the file upload control for use in our javascript. I do a substring on the file path and extract the file name by pulling back only the text after the last '\' and do the compare.
As my comment in the function says, returning true/false from a function called in the OnClientclick event determines whether a post back occurs. So if the user clicks yes in the confirmation box then a postback occurs, else if they click no then none occurs.
Hope that at least gets you going in the right direction.
Add the code below to your submit button
OnClientClick="return confirm('Are you sure you want to delete this file?')"
Edit as someone pointed out this will ask this question without taking in concern previous file and new one. It will do basic job.
My question is whether you doing this for edit mode or in new item mode. I mean are you editing item or adding new one on page you are interested to check?
I have a about 6 or 7 text boxes which needs to be validated to make sure they are not empty from server side code. So how I usually do this is, check each textbox 1 by 1 to ensure that they are not empty. Are there any other efficient methods to do this? I have searched on SO and have found out that adding all the textboxes to a list and using a for each is a much better method. Are there any other ways that this can be achieved? Thanx a lot in advance :)
Just check them each individually:
if (string.IsNullOrEmpty(this.NameTextBox.Text) ||
string.IsNullOrEmpty(this.AddressLine1TextBox.Text) ||
// etc...
)
{
// Handle me
}
Or possibly:
void CheckTextBox(TextBox textBox)
{
if (textBox == null)
{
throw new ArgumentNullException("textBox");
}
if (string.IsNullOrEmpty(textBox.Text))
{
// Handle me
}
}
void Validate()
{
CheckTextBox(this.FirstNameTextBox);
CheckTextBox(this.AddressLine1TextBox);
CheckTextBox(this.AddressLine2TextBox);
}
7 text boxes really isn't that many - explicitly checking each one keeps it simple and makes sure that others reading your code know what's going on, whereas messing around with collections is adding another layer of indirection, and makes it just slightly less straightforward to debug.
Keep it simple!
I agree with Kragen - your code may look "big" because of all the checks, but you are really writing exactly what the program needs to do in order to validate these things, so any sort of clever approach that reduces the number of lines of code you write isn't actually going to speed things up that much.
Question though: do you have to validate the textbox on the server? If you are only validating that the textbox isn't empty, I'd suggest using client side validation. That will save you server time and bandwidth, since your user won't be allowed to submit the form to your server until their browser has validated that they aren't empty.
You'd still want to validate on the server side (in case they don't have JavaScript enabled on their browser or they are attempting some kind of malicious behaviour).
The native ASP.NET way of client side validation involves adding an ASP.NET validation tag to your ASPX. It's actually quite easy. Here's an example on MSDN:
http://msdn.microsoft.com/en-us/library/aa479013.aspx#aspnet-validateaspnetservercontrols_topic3
I've simplified their code a bit to match your requirements:
<form runat="server">
<asp:TextBox id="TextBox1" runat="server" />
<asp:RequiredFieldValidator id="RequiredFieldValidator1" runat="server" ErrorMessage="Name is required!" ControlToValidate="TextBox1" />
<asp:TextBox id="TextBox2" runat="server" />
<asp:RequiredFieldValidator id="RequiredFieldValidator2" runat="server" ErrorMessage="Address is required!" ControlToValidate="TextBox2" />
<asp:Button id="Button1" onclick="Button1_Click" runat="server" Text="Button"></asp:Button>
</form>
I am developing a user control (ascx) in ASP.NET which uses javascript for manipulating controls. Currently the javascript code is inlined and uses <%= somecontrol.ClientID %> to get the control it needs.
I want to put the javascript file in external file but from external file I cannot use the above syntax for retrieving controls. I have read about possible solutions in this and this answers but the problem is that the user control can be placed multiple times on page. This means that the Controls array (mentioned in the answers) will be rendered several times with different items. As a result the script will not be able to retrieve the id it needs. If I put <%= ClientId %> in the name of array that holds items then I will have the same problem as I am trying to solve.
Any ideas?
Ok, a different approach, that I try to use a JavaScript-class style, and then initialize it for each control.
In the external javascript file, write your code as:
function oNameCls(ControlId1) {
this.ControlId1 = ControlId1;
this.DoYourWork1 = function() {
// use the control id.
// this.ControlId1
}
this.DoYourWork2 = function() {
// use the control id.
// this.ControlId1
}
}
And on the control do the call like that.
<script language="Javascript" type="text/javascript">
// init - create
var <%=this.ClientID%>MyCls = new oNameCls(<%=Control1.ClientID%>);
// do your work
<%=this.ClientID%>MyCls.DoYourWork1();
</script>
Hope now help better.
The way I solve this problem is to use CSS classes or place the controls within containers with known IDs and then traverse into the container's children to get the actual controls. For example:
<asp:TextBox ID="Something" runat="server" CssClass="mycontrol" ... />
Could be accessed via:
jQuery('.mycontrol');
Or:
<div id="ControlContainer">
<asp:TextBox ID="Something" runat="server" ... />
</div>
Could be accessed via:
jQuery("#ControlContainer input[type='text']");
The only real problem with this approach is you're tying your code to specific markup on the page, which can be a hassle if the markup changes a lot.
What about a hidden variable:
<input type="hidden" id="ClientId" value="<%=ClientId %>">
Then from your js:
$("#" + $("#ClientID").val())
Or, put the hash in:
<input type="hidden" id="ClientId" value="#<%=ClientId %>">
...
$($("#ClientID").val())
If you want to find a specific control when there could be multiple copies, this can't be done. How would the external javascript know which of the n controls you wanted?
How can rig the behavior up to a class and find the elements relative to the position of the action control, like this:
UserControl:
<div class="myControl">
<asp:Button id="MyButton" runat="server" Text="Click Me" />
<div style="display:none;">Show me!</div>
</div>
If you jQuery was written to be relative like this:
$(".myControl input").click(function() {
$(this).next().slideDown();
});
In this case, it doesn't matter what the specific IDs are, as long as you can navigate the DOM relatively to the controls you need. Even if it's more complex like .closest("div").next().find(".bob").prev()...whatever you need to get there works.