I have an ASP.NET web form where I have an hidden field, like this:
<form id="form1" runat="server" action="http://localhost/fa/Default.aspx">
<div>
<input id="requestData" type="hidden" name="requestData" value="" runat="server" />
<asp:Button ID="btnPOST" Text="POST" runat="server" OnClick="do_POST" />
</div>
</form>
On the method do_POST I have this:
protected void do_POST(object sender, EventArgs e)
{
//requestDataField is of the type protected global::System.Web.UI.HtmlControls.HtmlInputHidden requestData;
requestDataField.Text = "FOO!";
}
When I submit the form (by pressing the button), it goes to the server (an handler) wheer I have this:
string requestData = context.Request.Form["requestData"];
I get an empty string..
But if I assign a value like this:
<input id="requestData" type="hidden" name="requestData" value="FOO" runat="server" />
I get the "FOO"
What am I missing?
The reason why it's not doing it is because the method is called after the page has been post back. Meaning, it is actually working if you change .Text to .Value unfortunately by that time you have already read your form and it was an empty value. I remember working on a project where you could tell your form not to submit until a function has been run (but it was with a javascript that needed to run an complete before aspx submitted). You should try to see if there is a way to force your form to run your function BEFORE doing the postback.
Your do_POST method runs on the server, not on the client, and so is setting the value of the server-side object which represents the <input> control. Your context.Request.Form["requestData"] gets the value of the field from the client side data submitted in the POST request, which was never set, so it is blank.
If you want the onClick to be a client-side function, then you need to do it a little differently. Use the OnClientClick attribute (instead of onClick). Then create a javascript method to set the field value:
<asp:Button ID="btnPOST" Text="POST" runat="server" OnClientClick="do_POST" />
<script>
function do_POST() {
document.getElementById("requestData").value = "FOO!";
}
</script>
I tried your code and did few changes to it.
Change requestDataField.Text = "FOO!"; to requestData.Value = "FOO";
Also I added two buttons. One for do_POST function and the UseSubmitBehaviour property is set as False. The other one was to submit the form.
If you want to set it on client side then you will have to use Javascript.
Use "Value" instead of "Text" property for HtmlInputHidden control:
requestDataField.Value = "FOO!";
instead of
requestDataField.Text = "FOO!";
Related
I have a search textbox in asp. And I want it to send request to the server each time the text is changed there. I have a javascript function which sends request but it is not being called each time when I type something in the text box. How can I call javascript function from ASP textbox?
That is my textbox:
<asp:TextBox ID="search" name="Search" runat="server" onchange="javascript:text_changed();"></asp:TextBox>
That is my js function:
function text_changed() {
searchedword = document.getElementById("ContentPlaceHolder1_search").value;
SendRequest();
}
You should use onKeyPress event to call the function.
<asp:TextBox ID="search" name="Search" runat="server" onKeyPress="javascript:text_changed();"></asp:TextBox>
Shivam's answer is right. You can use KeyPress event to get users key strokes with that event.
But i want to inform you, you should not use ASP.NET control ids like that :
document.getElementById("ContentPlaceHolder1_search").value;
Because you'll get errors if you put your textbox somewhere else in html hierarchy, ASP.NET regenerates it's id.
Try that one, instead :
function text_changed(textObj) {
searchedword = textObj.value;
SendRequest();
}
<asp:TextBox ID="search" name="Search" runat="server"
onKeyPress="javascript:text_changed(this);"></asp:TextBox>
The functionality you asking can achieve by
Use onkeyup or onkeydown instead.
This will then run the function when you type or click on the textbox. You can also then detect the keycode of the event, and prevent the function if you dont want it to run for certain keys.
Use the below code
$("#search").keydown(function(){
text_changed();
});
$("#search").keyup(function(){
text_changed();
});
Demo Here
give it a try :)
$("#search").change(function(){
//your ajax codes
});
<script>
function multy(val)
{
alert(val.value+"--"+val.id);
}
</script>
<input id="txtdemo" type="text" onchange="multy(this);"></br>
<input id="txtdemo" type="text" onchange="multy(this);">
</input>
Thanks... :)
I'm grappling with an issue where the site is asp.net/C# but controls on the .aspx pages are HTML and I'm not sure how well it would go over if I would change everything into asp.net controls. Also the change is minor. I was tasked to add a check box, as in <input type="checkbox" name="disableFeatureManager" runat="server" id="disableFeatureManager" />Disable Feature Manager and in the .cs page I want to check if the box is checked and make decisions based on that, but the control's checked property is always false. The submit button is also a HTML control: <input type="submit" value="Start" name="submitButton" />
In the Page_Load ckecking if check like this returns false.
if (disableFeatureManager != null && disableFeatureManager.Checked)
nextURL.Append(FeatureManagerChoices.CreateQueryStringFromFormData(Request.Form));
You could keep your checkbox as an Html server control by doing the following:
<input type="checkbox" name="disableFeatureManager" runat="server" id="disableFeatureManager" />
Then you could change your button to a web control as follows:
<asp:Button ID="submitStart" runat="server" OnClick="btn1_Click" Text="Start" ClientIDMode="Static" />
The only difference with the above rendered HTML will be the name that is output but you will have an Id that is submitStart due to the ClientIdMode being static, if you need a friendly consistent Id for javascript manipulation.
To wire in the event add this code which will read the value from the checkbox:
protected void btn1_Click(object sender, EventArgs e)
{
var isChecked = disableFeatureManager.Checked;
}
As I mentioned before, I was trown into the deep end of MVC. Co-worker offered a simple answer(as least in this case):
bool isChecked = false;
if(Request["disableFeatureManager"] != null)
isChecked = (Request["disableFeatureManager"].ToLower() == "on");
if (!isChecked)
nextURL.Append(FeatureManagerChoices.CreateQueryStringFromFormData(Request.Form));
I think this can be further simplified in to one IF statement.
How can I check whether a particular button was clicked or not in ASP.NET?
I think I need to perform some operation on Page_Load. This shouldn't be entering to Button_Click event to find. Is there any way that I can find where it was clicked or not on Client Side and take it to Page_Load?
Background: Basically __EVENTTARGET and __EVENTARGUMENT , These two Hidden controls are added to the HTML source, when ever any autopostback attribute is set to true for any of the web control.
The __EVENTTARGET hidden variable will tell the server ,which control actually does the server side event firing so that the framework can fire the server side event for that control.
The __ EVENTARGUMENT variable is used to provide additional event information if needed by the application, which can be accessed in the server.
So we can easily get the control causing postback using:Request.Params.Get("__EVENTTARGET");
PROBLEM:
The method: Request.Params.Get("__EVENTTARGET"); will work for CheckBoxes, DropDownLists, LinkButtons, etc.. but this does not work for Button controls such as Buttons and ImageButtons
The Button controls and ImageButton controls does not call the __doPostBack function. Because of this, the _EVENTTARGET will always be empty. However, other controls uses javascript function __doPostBack to trigger postback.
So, I will suggest to do something as below. Add an OnClientClick property to the buttons. Also, define a hiddenField in your Markup, whose value will contain the actual button causing postback.
<asp:Button ID="Button1" runat="server" Text="Button"
OnClientClick = "SetSource(this.id)" />
<asp:ImageButton ID="ImageButton1" runat="server"
OnClientClick = "SetSource(this.id)" />
<asp:HiddenField ID="hidSourceID" runat="server" />
On the OnClientClick property of the Button and ImageButton Call the SetSource JavaScript function
<script type = "text/javascript">
function SetSource(SourceID)
{
var hidSourceID =
document.getElementById("<%=hidSourceID.ClientID%>");
hidSourceID.value = SourceID;
}
</script>
Here onwards, you can very easily check in your Page_Load as to which Control caused postback:
if (IsPostBack)
{
string CtrlName;
CtrlName=hidSourceID.Value;
}
I just got the same trouble, have to do some logic judgement in the Page_Load method to treat different event(which button was clicked).
I realize the arm to get the as the following example.
The front end aspx source code(I have many Buttons with IDs F2, F3, F6, F12.
<Button Style="display: none" ID="F2" runat="server" Text="F2:Cancel" OnClientClick="SeiGyo(this)" OnClick="F2_Click" />
<Button Style="display: none" ID="F3" runat="server" Text="F3:Return" OnClientClick="SeiGyo(this)" OnClick="F3_Click" />
<Button Style="display: none" ID="F6" runat="server" Text="F6:Run" OnClientClick="SeiGyo(this)" OnClick="F6_Click" />
<Button Style="display: none" ID="F12" runat="server" Text="F12:Finish" OnClientClick="SeiGyo(this)" OnClick="F12_Click" />
The back end aspx.cs source code, what I need to do is judge which button was clicked when Page_Load was triggered. It seems a little stupid, but works.
In your situation, the button be clicked will be added into dic. I hope that will be helpful to some one.
Dictionary<string, string> dic = new Dictionary<string, string>();
foreach(var id in new string[]{"F2","F3","F6","F12"})
{
foreach (var key in Request.Params.AllKeys)
{
if (key != null && key.ToString().Contains(id))
dic.Add(id, Request[key.ToString()].ToString());
}
}
The UniqueID of the button will be in Request.Form["__EVENTTARGET"]
This question is already answered at: ASP.NET : Check for click event in page_load
You can try using the hidden field. Make the client side event on the OnclientClick event and try setting the value of hidden field, may be true or false depending on the condition.
And on the page load you can check the value of Hiidden field.
function click()
{
// set the hidden field here
}
And on the page load, simply check the value.
if(HiddenFieldName.Value=="true")
{
//perform the action
}
private bool button1WasClicked = false;
private void button1_Click(object sender, EventArgs e)
{
button1WasClicked = true;
}
if ( button1WasClicked== false)
{
//do somthing
}
I have two asp:Labels, the first of which is replaced with a few buttons and the second with a list of items.
I want to click on the buttons to filter the items.
The contents of the buttons are added programmatically by replacing the text with html and works fine.
asp:
<form id="form1" runat="server">
<asp:Label id="filters" runat="server" Text="Filters here"/>
<asp:Label id="itemList" runat="server" Text="List of items here"/>
</form>
resultant html of filters label:
<input type="submit" onclientclick="Load_Items(0)" runat="server" value="First"/>
<input type="submit" onclientclick="Load_Items(1)" runat="server" value="Second"/>
<input type="submit" onclientclick="Load_Items(2)" runat="server" value="Third"/>
relevant c#:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Load_Items(0);
}
}
public void Load_Items(int filterType)
{
//code to load items (pseudo below)
for each row in list
if filterType = itemType
build string
replace second label with string
}
On page load everything happens just as I want it to with the contents being filtered by the first item (hence Load_Items(0)), and if I manually change the 0 to another number in Page_Load, it filters by the other types, but if I click the buttons which are programmatically added, nothing happens other than what looks like the page refreshing.
I know the post back check is working by adding a text replacement before and inside it.
I've also added an asp:button to make sure it's not something to do with the way the buttons are added as below (with some extra things recommended from searches):
<asp:Button runat="server" CausesValidation="False" onclientclick="Load_Items(2); return false;" text="Submit" />
So what could be the issue?
The OnClientClick property specifies the javascript to run in the browser when the button is clicked. Since you probably don't have a javascript function called Load_Items, this will generate a script error, and the button will then cause the form to post back.
The server-side Click event will fire on the server, but doesn't allow you to pass a parameter. You will only get the button instance and an empty EventArgs instance.
You might be better off using the Command event, combined with the CommandArgument property.
<asp:Button runat="server" CommandArgument="2" OnCommand="Load_Items" ...
The event handler would use the CommandArgument property of the CommandEventArgs to access the argument from the clicked button:
protected void Load_Items(object sender, CommandEventArgs e)
{
Load_Items(Convert.ToInt32(e.CommandArgument));
}
Well, that's the common problem which I think every asp.net developer deals some time. The common part of it, that asp.net event system doesn't work, as windows forms.
Page object, and all controls on that page, have lifecycle events, that are triggered during any request, even when it's from update panel.
As you create those controls by code, you have to keep in mind, that all events for those controls should work as part of Page object. That's why you have to create those object in Page_Init event, before all other control's event would be triggered.
Please also keep in mind that you have to create those controls as asp.net objects:
var btn = new Button();
But not by simply adding html markup. And you have to recreate them on each request, following that one, when they were created.
Please take a look on my another answer.
I was wondering if you guys could help me understand hidden fields, since I don't think I am getting them to work.
On the aspx page I have:
<asp:HiddenField ID="hidVal" value="" runat="server" />
On a button click I have a JavaScript function called
<button type="button" id="search" onclientclick="search_click()">Search</button>
With the function being
function search_click() {
document.getElementById('hidVal').Value = "1";
<% save(); %>
}
In aspx.cs I have a function that does this:
using (System.IO.StreamWriter file = new System.IO.StreamWriter(#"C:\Users\fgreene\Desktop\savedAdresses.txt", true))
{
file.WriteLine(hidVal.Value);
}
After clicking the button I look into the file and there is no change.
Is my approach correct or am I not understanding how this works?
Putting <% save(); %> in a JavaScript function in an aspx page causes save to be run when the page is built on the server, not when the surrounding JavaScript function is called on the client. At this point, the hidden field is empty, so your file gets a blank line written to it. When the user clicks the button, the hidden field is filled, but there's nothing to tell the server that this has happened.
What you need to do instead is something like:
// In your aspx, for the javascript function: remove the call to save,
// use the correct ID for the hidden field
function search_click() {
document.getElementById('<%= hidVal.ClientID %>').Value = "1";
}
// In your aspx in place of the button put
<asp:Button id="search" runat="server"
onclientclick="search_click(); return true;" onclick="search_click">
Search
</asp:Button>
// This results in a button that calls the javascript function on click, and
// then posts back to the server saying that the button has been clicked
// In your C#, this function gets called when the client posts back to
// say that the button has been clicked.
public protected void search_click(object sender, EventArgs e)
{
using (System.IO.StreamWriter file = new System.IO.StreamWriter(
#"C:\Users\fgreene\Desktop\savedAdresses.txt", true))
{
file.WriteLine(hidVal.Value);
}
}
You'll need to reference the client ID of the hidden field, which is probably not hidVal, as the actual client side ID generated in the HTML will be based on the parent control's naming container. There's two ways to fix this. First, you could make the client ID static on the control (which basically tells ASP.NET make the ID exactly what I said.):
<asp:HiddenField ID="hidVal" value="" ClientIDMode="Static" runat="server" />
Second, you can look up the ClientID property from the server when you generate your JavaScript:
document.getElementById('<%= hidVal.ClientID %>').Value = "1";
This would render out the actual client ID directly in the JavaScript code. Either approach is probably fine, but the second one would only work if the JavaScript is embedded directly in your ASPX file and not in a static .JS file.
Calling server side methods:
The second part of your question is about calling server side code when the button is pressed. You should do this by attaching an OnClick handler to your button:
<button runat="server" id="BtnSearch" onclientclick="search_click()" OnClick="btnSearch_Click">Search</button>
When the button is pressed, the page will be posted back and the btnSearch_Click event handler will be called. You'll then be able to handle any server side logic, as well as check the value of your hidden field. Hope this helps!
What you're trying to do is execute a server side function (save) via a client side call. This won't work as it is calling save() when the page first loads and then putting the return value (which is probably nothing) into the code where you put
<% save(); %>
Instead you need your button to fire the save function, but fire your javascript first. You do this by creating an asp:button (which renders as ) and then adding both an "OnClientClick" (for your javascript) and "OnClick" (for your server side function).
<asp:Button id="btnSearch" runat="server" OnClick="btnSearch_Click" OnClientClick="search_click()" text="Search" />
Then in your C# code you need the method to be named the same as the OnClick value:
protected void btnSearch_Click(object sender, EventArgs e)
{
using (System.IO.StreamWriter file = new System.IO.StreamWriter(#"C:\Users\fgreene\Desktop\savedAdresses.txt", true))
{
file.WriteLine(hidVal.Value);
}
}
The easiest way to create your server side function is to double click on the button in design view, as it will add the correct method call for you.
Hope this helps.
You can change hidden field value in both serverside and client side events.
Change value in client side
<script type="text/javascript">
function setvalue() {
document.getElementById('hidVal').value = "1";
}
</script>
<div>
<asp:HiddenField ID="hidVal" value="" runat="server" />
<br />
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="setvalue();" />
</div>
Change value in serverside
<div>
<asp:HiddenField ID="hidVal" value="" runat="server" />
<br />
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
</div>
protected void Button1_Click(object sender, EventArgs e)
{
hidVal.Value = "1";
}