I have webapplication in c# asp.net 4.0
I have User Control in that I have written javascript :-
<script>
function SetValue() {
alert(document.getElementById('offSetClient').value);
}
</script>
<asp:HiddenField ID="clientDateTime" runat="server" />
<asp:HiddenField ID="offSetClient" runat="server" Value="Test"/>
and this User Control added into a web form.
Please suggest me how can I call this javascript on User Control page load.
You can use Page.ClientScript.RegisterStartupScript to attain this.
protected void Page_Load(object sender, EventArgs e)
{
Page.ClientScript.RegisterStartupScript(GetType(), "ShowAlert", "SetValue('" + offSetClient.ClientID + "');", true);
}
Please add an input parameter for the function to get the object of hidden field and pass the same from function.
<script type="text/javascript">
function SetValue(objHdn) {
alert(document.getElementById(objHdn).value);
}
</script>
Related
I got the process of getting the value of input field in c# in here:
Get value from input html in codebehind c#
I have a hidden input field in my aspx page like this:
<input type="hidden" id="lblCountry_val" runat="server" />
Where the value of the hidden field is put through jquery:
<script type="text/javascript">
$(function () {
BindUserInfo();
})
function BindUserInfo()
{
document.getElementById('lblCountry_val').value = window.strcountry;
}
</script>
<script type="text/javascript" src="http://smart-ip.net/geoip-json?callback=GetUserInfo"></script>
But When I am trying to get the value in Page_Load event in code behind with this:
Response.Write(lblCountry_val.Value);
Nothing is being printed. How come?
EDIT
I have done this by changing the hidden input field to an invisible textbox and then putting "name" attribute in the tag.
<input type="text" id="lblCountry_val" name="lblCountry_val" runat="server" style="display:none" />
And in the code behind:
var txt=Request.Form["lblCountry_val"];
Though I have not a clear idea how it was done.
First Method -
In aspx, When you set a value to html field using Java script, Field's value doesn't appear in code behind file(aspx.cs). So you have to do additional page post back for set a value to hidden field and then you can able to catch the value in code behind file.
Second Method -
Using tag, submit hidden field data to relevant aspx page.Then you can catch the value using Request.Form["lblCountry_val"] array.
You should write
document.getElementById('<%=lblCountry_val.ClientID%>')
This happens because in the most cases the serve side Id of a control is different from its clientId. The way to take it is the above.
Try this...
JavaScript
<script>
$(document).ready(function () {
var test = "1";
$("<%=hdn_audio_length.ClientID%>").val(test);
});
</script>
Html
<asp:HiddenField runat="server" ID="hdn_audio_length" />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="button1" runat="server" Text="Click" OnClick="button1_Click" />
C#
protected void button1_Click(object sender, EventArgs e)
{
TextBox1.Text = hdn_audio_length.Value;
}
Here's an example setting hidden fields on submit click.
`<script>
$(document).ready(function () {
$("#submit").click(function () {
$("#<%= ccnum.ClientID%>").val($("#cc-num").val());
$("#<%= expdate.ClientID%>").val($("#cc-exp").val());
$("#<%= cvc.ClientID%>").val($("#cc-cvc").val());
});
});
</script>`
Browse and Upload with using asp:FileUploadcontrol is working perfectly fine.
But It is two step process. First we have to browse and then select the file.
I want it working in single step So for making it single step I tried the following code:
protected void Button1_Click(object sender, EventArgs e)
{
//to launch the hidden fileupload dialog
ClientScript.RegisterStartupScript (GetType(),
"hwa", "document.getElementById('fileupload').click();", true);
//Getting the file name
if (this.fileupload.HasFile)
{
string filename = this.fileupload.FileName;
ClientScript.RegisterStartupScript(GetType(), "hwa", "alert('Selected File: '" + filename + ");", true);
}
else
{
ClientScript.RegisterStartupScript(GetType(), "hwa", "alert('No FILE has been selected');", true);
}
}
In this code, there is one fileUpload control that is being invoked on Button1_Click. Ideally it should execute the first line then A file Upload control should be shown and after selecting a file or canceling the dialog, flow should go to next line. But dialog is showing up after full function execution finishes.
Because of this asynchronous or not expected execution flow if (this.fileupload.HasFile) is returning false(because user has not been asked to select any file yet) and I am not getting the selected file name.
Can we modify this code to achieve file upload in single step? Or if any other way is possible to do this?
Note- I have asked not to use window forms and Threads. So solution by using these two is not acceptable.
You are missing the fact there is a client side/server side disconnect in the web environment.
Your line: ClientScript.RegisterStartupScript (GetType(),"hwa","document.getElementById('fileupload').click();", true); is client side code and will not be executed until the serverside script is comleted and the resulting HTML/javascript/CSS returned to the browser as it is client side javascript. YOu want to be leveraging the onchange event of the file upload control.
The question should help you out: ASP.NET FileUpload: how to automatically post back once a file is selected?
this is not exactly what you are looking for but it does what you want. difference is that instead of clicking a separate button you have to click the Browse button. and when you press the Open button, the page will postback. I have used JQuery for this. here's my code
ASPX
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.9.1.min.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="fileupload1" runat="server" />
<asp:Button ID="btn" runat="server" OnClick="btn_Click" Text="upload" style="display:none" />
</div>
<script type="text/javascript">
var isfirst = true;
$(function () {
$('#<%= fileupload1.ClientID %>').on('change', function (e) {
console.log('change triggered');
$('#<%= btn.ClientID%>').trigger('click'); // trigger the btn button click which i have hidden using style='display:none'
});
});
</script>
</form>
</body>
Code behind
protected void btn_Click(object sender, EventArgs e)
{
//TODO
}
For the ones who land here late,
<div>
<asp:FileUpload ID="fu" runat="server" CssClass="bbbb" onchange="clickSeverControl()"/>
<asp:LinkButton Text="Upload" ID="lnkUpload" runat="server" OnClientClick="showUpload();return false;" OnClick="lnkUpload_Click"/>
</div>
hide the file control with css
<style>
.hiddenStyle {
visibility:hidden;
}
</style>
on client click event of link button trigger the click of file upload control
function showUpload() {
document.getElementById("fu").click();
}
on change event trigger the server side click
function clickSeverControl() {
__doPostBack('<%= lnkUpload.ClientID %>', 'OnClick');
}
on server click save the uploaded file
protected void lnkUpload_Click(object sender, EventArgs e)
{
fu.PostedFile.SaveAs(Server.MapPath("~/Upload") + "/" + fu.PostedFile.FileName);
}
Thanks for the other answer I have just combine two example and got the solution for my problem in my project
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.9.1.min.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="fileupload1" runat="server" />
<asp:Button ID="btnUploadBulk" runat="server" OnClick="btn_Click" Text="upload" style="display:none" />
</div>
<script type="text/javascript">
var isfirst = true;
$(function () {
$('#<%= btnUploadBulk.ClientID%>').on('click', function (e) {
showUpload();
})
});
function showUpload() {
var control = document.getElementById("<%= FileUploadControl.ClientID %>");
control.click();
}
</script>
</form>
Code Behind
protected void btn_Click(object sender, EventArgs e)
{
//TODO
}
This worked for me
I need to know if asp control (Button) is clicked or not using jQuery. This is button coding.
How can I pop up an alert box if someone hit a button using jQuery.
<asp:Button ID="delete_checked_box_button_id" OnClick="deletechecked_box_onclick" runat="server" Text="Delete Checked" />
Thanks in advance.
When you set the ClientIDMode property to Static you can use the Id you set:
$(document).ready(function() {
$('#delete_checked_box_button_id').on('click', function(e) {
alert('Button clicked');
});
}
$('#<%=delete_checked_box_button_id.ClientID %>').click(function() {
alert("Handler for .click() called.");
});
You don't need jQuery, you can use the button's property onClientClick
See this example in MSDN
<script type="text/javascript">
function BuyG2() {
alert('Hai Jquery');
}
</script>//jquery in sourse
protected void Button1_Click(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "tmp", "<script type='text/javascript'>BuyG2();</script>", false);
}//ASP Button Click Event
<script language="javascript" type="text/javascript">
function myjavascriptfn()
{
//debugger;
var strValue= "test";
return strValue
}
How do I call this javascript function in my code behind and proceed appropriately with respective of return values.
You can easily declare JavaScript to be run on the Client using
ScriptManager.RegisterStartupScript(this, this.GetType(), "launchpage", "
function javascriptfn() {
var strValue= 'test';
return strValue;
}
document.getElementById('"+HiddenField1.ClientID+"').value = javascriptfn();
document.getElementById('"+saveProgressButton.ClientID+"').click();
", true);
note: I have divided out the JavaScript out onto multiple lines to make it easier to read but it should all be on one line.
Your problem comes with the second part of the question, sending the data back, you will most likely need a postback (partial or full or handle it with AJAX.
I would add an updatepanel with a asp hiddenfield and a hidden button to trigger it, populate the value of the hidden field with whatever this function is for had have some code in your code behind to capture the event.
<asp:UpdatePanel ID="responcetable" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:HiddenField ID="HiddenField1" runat="server" />
<asp:Button ID="saveProgressButton" runat="server" Text="Button" CssClass="displaynone" />
</ContentTemplate>
<Triggers><asp:AsyncPostBackTrigger ControlID="saveProgressButton" EventName="theeventtodealwiththis" /></Triggers>
</asp:UpdatePanel>
and on the serverside
protected void theeventtodealwiththis(object sender, EventArgs e)
{
// some logic to handle the value returned
}
I have an image button on a pop up page which is opened by another page
<asp:ImageButton
ID="Button_kalem_islemikaydet"
runat="server"
CausesValidation="False"
ImageUrl="~/images/butonlar/buyuk/Kaydet.jpg"
meta:resourcekey="Button_kalem_islemikaydetResource1"
OnClick="Button_ust_islemikaydet_Click"
OnClientClick="f2()"
Width="100" />
f2() is
<script type="text/javascript">
function f2() {
opener.document.getElementById("TextBox1").value = "hello world";
opener.document.getElementById("HiddenField1").value = "hello world";
window.opener.location.href = window.opener.location.href;
}
</script>
And Button_ust_islemikaydet_Click is another method implemented in aspx.cs file and it updates the database tables which are shown in the parent page in a GridView.
What I am trying to do is to doPostBack I mean refresh the opener(parent) page.And with these above codes refresh is working.However, parent page still shows the same data before the refresh.And the reason is that OnClientClick works before OnClick method
So my question is that is there any way I can run the method on OnClick and finish it and then run the OnClientClick method?
<form id="aspnetForm" runat="server">
<asp:Button Text="Click Me" ID="ClickMeButton" OnClick="ClickMeButton_OnClick" runat="server" />
<asp:HiddenField runat="server" ID="UpdateOpenerHiddenField" Value="false" />
<script type="text/javascript">
//1st approach
var updateOpenerField = window.document.getElementById("<%= UpdateOpenerHiddenField.ClientID %>");
if (updateOpenerField.value === "true") {
f2();
updateOpenerField.value = "false";
}
// for the 2nd approach just do nothing
function f2() {
alert("Hello, opener!");
}
</script>
</form>
protected void ClickMeButton_OnClick(object sender, EventArgs e)
{
//1st approach
UpdateOpenerHiddenField.Value = "true";
// 2nd approach
ClientScript.RegisterStartupScript(this.GetType(), "RefreshOpener", "f2();", true);
}
No, you can't run server side code (OnClick event handler) before client side. OnCLientClick event was added to perform some validation before post back. There is only one way to do it - update the f2 method and post data on server via ajax
You can put your javascript inside a PlaceHolder tag which you make visible in your server-side OnClick handler.
aspx code:
<asp:PlaceHolder id="refreshScript" visible="false" runat="server">
window.opener.location.href = window.opener.location.href;
window.close();
</asp:PlaceHolder
cs code:
protected void button_Click(Object sender, EventArgs e) {
// do whatever
refreshScript.Visible = true;
}