How to pass codebehind information into javascript function - javascript

I have a button in my updatepanel and I'm trying to call a javascript function (after it does it's processing).
I put this code inside the Page_Load:
Dim cstype As Type = Me.GetType()
Dim cs As ClientScriptManager = Page.ClientScript
cs.RegisterStartupScript(cstype, "modalScript", "jsModal('" + msg + "');", True)
keywordSearch.Attributes.Add("onclick", "jsModal('" + msg + "');")
Client Side javascript:
function showModal(msg) {
$("#modal-content, #modal-background, #modal-close").toggleClass("active");
var returnString = msg;
$('#modal-content div').each(function (index) {
$(this).html(returnString);
});
}
How do I pass the values I gather from the server side click event into the javascript function?

I suppose your question is about webform. In this case try this in the aspx
<script type="text/javascript">
$(document).ready(function() {
$("#buttonTest").click(function () {
$("#<%= hiddenField.ClientID%>").val("TEST");
});
});
</script>
<asp:HiddenField runat="server" ID="hiddenField" />
<button id="buttonTest">
Change value hidden field
</button>
<asp:Button runat="server" Text="POST" ID="postButton" />
And this in the CodeBehind
Private Sub postButton_Click(sender As Object, e As EventArgs) Handles postButton.Click
YourLogic(hiddenField.Value)
End Sub

Related

vbHow to get javascript value in asp.net?

How to get javascript value in asp.net?
I am using vb asp.net, javascript and html
When user click on 'pay' button in html code, than I will to run some code in javascript, than pass TokenHF.value in asp.net
issue is that: inside page_load() function, test TokenHF.value will be alway empty.
this is bc of on load function. any idea how to get TokenHF.value in asp.net?
vb asp.net code:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim test = TokenHF.value
end sub
html code:
<asp:hiddenfield id="TokenHF" runat="server"></asp:hiddenfield>
<div id="card-number-element class="field"></div>
<div id="card-expiry-element" class="field"></div>
<div id="card-cvc-element" class="field"></div>
<input id="postal-code" name="postal_code" class="field" placeholder="90124" />
<button type="submit">pay</button>
javascript code:
<script>
var stripe = Stripe('pk_test_982wyfu9sfdsf');
var elements = stripe.elements();
function setOutcome(result) {
if(result.token){
document.getElementById('<%= TokenHF.ClientID %>').value = result.token.id;
}
}
document.querySelector('form').addEventListener('submit', function (e) {
e.preventDefault();
var options = { address_zip: document.getElementbyID('postal-code).value,
};
stripe.createToken(cardNumberElement, options).then(setOutCome);
})
</script>

How to call Javascript function from server side asp.net

I have a Textbox in GridView I want to change the Label.Text if the text in Textbox is changed. But I am not able call javascript function written in .cs page. Is there any mistake in TbUnitCost_TextChanged method.
This is my aspx page
<ItemTemplate>
<asp:TextBox Style="text-align: right" ID="TbUnitCost" runat="server" Width="80px" Text='<%#Bind("Unit_Cost")%>' AutoPostBack="true" OnTextChanged="TbUnitCost_TextChanged" TextMode="Number"></asp:TextBox>
</ItemTemplate>
Code behind Page is as follows
protected void TbUnitCost_TextChanged (object sender, EventArgs e)
{
GridViewRow currentRow = (GridViewRow)((TextBox)sender).Parent.Parent;
int rowNo = currentRow.RowIndex;
string gridName = "GridWorkExpenses";
TextBox tbunitCost = (TextBox)currentRow.FindControl("TbUnitCost");
int row = Convert.ToInt32(tbunitCost.Text);
tbunitCost.Attributes.Add("onchange","javascript:calculateTotalCost('"+rowNo+"','"+gridName+"');");
}
and javascript Function is:
<script type ="text/javascript">
function calculateTotalCost(rowNo, GridName) {
if (GridName== 'GridWorkExpenses') {
var rowscount = document.getElementById('<%=GridWorkExpensesSheet.ClientID%>').rows.length;
return calculateTotalUnitCost("GridWorkExpensesSheet", rowscount,rowNo);
}
}
</script>
Try using this:
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Script", "CalculateTotalCost", true);
Describe any further problem (if there is any).
ScriptManager.RegisterStartupScript(this, this.GetType(), "Script", "<script type='text/javascript'>CalculateTotalCost</script>", false);
is another method
This is a very old discussion [1]:Difference between RegisterStartupScript and RegisterClientScriptBlock?
Please refer this too.
hi you must write all of command in the one string
ScriptManager.RegisterClientScriptBlock((sender as Control), GetType(), "jQueryCommand", "$('.MenuLoginLink').hide();$('.MenuUsername').show();$('.MenuUsername').text('" + Currentmember.Mobile + "');$('.MenuExit').show();" +
" $('.btnLoginInFriends').hide();$('#HiddenSession').val('" + int.Parse(Session["CurrentUserID"].ToString()) + "');", true);

VB call javascript resource code behind

I'm trying to pass a string and call a javascript function from the code behind in vb.net, once I click a button. The javascript is in a separate file.
Below is the code for the button:
/MyProject/myfile.aspx
<HTML>
...
...
<asp:textbox id="txtSearch" runat="server" Width="120px" CssClass="midField"></asp:textbox>
<input class="midBtn" id="btnSearch" type="button" value="Search" name="btnSearch" runat="server">
...
...
<script src='<%= Page.ResolveClientUrl("~/script/functions/myFunc.js")%>' ></script>
</HTML>
/MyProject/myfile.aspx.vb
Private Sub btnSearch_ServerClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearch.ServerClick
Dim searchString As String
searchString = txtSearch.Text
Dim rsname As String = Page.ResolveClientUrl("~/script/functions/myFunc.js")
Page.ClientScript.RegisterStartupScript(Me.GetType(), "mySearch", "mySearch('" & searchString & "')", True)
End Sub
/MyProject/script/functions/myFunc.js
function mySearch(searchString){
// ...
// logic for mySearch
// ...
}
I can't get the javascript function to be called and I need to reference the .js file at the end of my .apsx page. The error I get from the debugger is Uncaught ReferenceError: mySearch is not defined, please help.
If the criterion of choice is a dropdown, probably a better solution (I used jquery) is put the js file at the end of page, and check the dropdown value from javascrpit (here set as variable) and intercept the postback of .NET button:
<script type="text/javascript">
$(document).ready(function () {
var dropdown = 1;
$('.midBtn').click(function () {
if (dropdown == 1) {
mySearch($('.midField').val());
return false;
} else {
// ... postback
}
});
});
</script>
In this case you must be sure that the classes selector (midBtn and midField) are unique.

Changing HiddenField value in codebehind no changing in Javascript function in order to use showModalDialog

In my Vb .net code-behind (Visual Studio 2005), in a method fired by click event:
hdnUrl and hdnParameters are hiddenFields
Protected Sub btnExample_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExample.Click
.
.
.
hdnUrl.Value = "Mypage.aspx?i=" & SomeCveDefinedInCodeBehind.Tostring & "&u=" & OtherCveDefinedInCodeBehind.Tostring
hdnParameters.value = "resizable: no; scroll: no; center: yes; dialogHeight: 525px; dialogWidth:750px; status: no;"
ScriptManager.RegisterClientScriptBlock(Page, Page.GetType, DateTime.Now.ToString, "<script type='text/javascript'> ShowWindow(); </script>", False)
.
.
.
In my page:
<asp:Content ID="Content3" ContentPlaceHolderID="cph3" runat="Server">
.
.
.
<asp:HiddenField ID="hdnUrl" runat="server" Value="" />
<asp:HiddenField ID="hdnParameters" runat="server" Value="" />
<asp:HiddenField ID="hdnResult" runat="server" Value="" />
<script language="javascript" type="text/javascript">
function ShowWindow()
{
alert('i am here');
var url = document.getElementById('<%= hdnUrl.ClientID %>').value;
var Parameters = document.getElementById('<%= hdnParameters.ClientID %>').value;
//For test:
alert(url); //------ i need to get here: "My page.aspx?...", but i always get: ""
alert(parameters); // i need to get here my parameters, but i always get: ""
.
.
.
var dialogWin = window.showModalDialog(url, "some text", parameters); //showModalDialog window, will return a data that i need in CodeBehind
document.getElementById('<%= hdnResult.ClientID %>').value=dialogWin.result;
//Then i could manage the result, in code-behind
}
</script>
</asp:Content>
Only if in the hidden field definition i set:
<asp:HiddenField ID="hdnUrl" runat="server" Value="My text" />
i can get this text in the javascript alert, but i need define the text in code-behind
Thanks for your Help and suggestions.
is there another way for pass url and parameters, to the window.showModalDialog???
or another way for get the result of the window.showModalDialog in code.behind???
Watch the casing on your Parameters variable. Also try using RegisterStartupScript instead of RegisterClientScriptBlock. The difference is the former will put your javascript at the bottom of the page while the latter puts it at the top. This will cause the script to run before the document it fully loaded.
ScriptManager.RegisterStartupScript(Page, Page.GetType, DateTime.Now.ToString, "<script type='text/javascript'> ShowWindow(); </script>", False)

BlockUI during partial postback through JavaScript

I have an ASP.NET page (WebForm1) that opens a modal dialog WebForm2 (via OpenForm2() js function) for some further processing. Upon closing the dialog I just update the UpdatePanel via JavaScript. Now the problem is, during this js call it doesn't block the UI.
This is only happening when I am calling the OpenForm2 js method from the server side (Button1_Click). As the UI already went into block mode, upon closing the WebForm2 it doesn't wait for the completion of partial postback (JavaScript) and unblocks the UI.
If I directly call the OpenForm2 js function in OnClientClick tag of the button (Button 2 in the sample), it works well and keeps blocking the UI till completion of postback.
I tried wrapping the partial postback js code in an add_endRequest, but in that case it keeps calling the refreshUpdatePanel() js method, hence blocking/unblocking the UI keeps going on. May this be happening due to two add_endRequest used on a page in that case?
Any assistance is highly appreciated in this regard.
NOTE: I have used jQuery blockUI for blocking the page during partial postbacks.
The code sample for the WebForm1 page is as follows. (The WebForm2 aspx page just have a button to close the dialog and a related js function).
WebForm1.aspx
<head runat="server">
<title></title>
<script src="js/jquery-1.6.1.min.js" type="text/javascript"></script>
<script src="js/jquery.blockUI.js" type="text/javascript"></script>
<script type="text/javascript">
function OpenForm2() {
var url = "WebForm2.aspx";
var width = 950;
var height = 455; // screen.availHeight - (120 + 65);
// open modal dialog
obj = window.showModalDialog(url, window, "dialogWidth:" + width + "px; dialogHeight:" + height + "px; center:yes");
// partial postback to reflect the changes made by form2
refreshUpdatePanel();
//Sys.WebForms.PageRequestManager.getInstance().add_endRequest(refreshUpdatePanel);
// ** here it doesn't wait for the completion and unblocks the UI **
}
function refreshUpdatePanel() {
//window.__doPostBack('UpdatePanel1', '1');
// a timeout/delay before a client side updatepanel postback. That compelled the UI to go in blocking again with a little screen flickering.
setTimeout('__doPostBack("<%= UpdatePanel1.ClientID %>", "1")', 0);
}
$(document).ready(function () {
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);
$.blockUI.defaults.css = {};
function InitializeRequest(sender, args) {
// Whatever you want to happen when the async callback starts
$.blockUI();
}
function EndRequest(sender, args) {
// Whatever you want to happen when async callback ends
$.unblockUI();
}
});
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" OnLoad="UpdatePanel1_Load">
<ContentTemplate>
<asp:Label ID="Label2" runat="server" Text=""></asp:Label><br />
<asp:Button ID="Button1" runat="server" Text="Button 1" OnClick="Button1_Click" />
<asp:Button ID="Button2" runat="server" Text="Button 2" OnClientClick="OpenForm2();return false;" />
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
WebForm1.aspx.cs
protected void Button1_Click(object sender, EventArgs e)
{
// some server side processing here
System.Threading.Thread.Sleep(1000);
// then calling javascript function to open form2 as modal
ScriptManager.RegisterClientScriptBlock(UpdatePanel1, UpdatePanel1.GetType(), "Button1Click", "OpenForm2();", true);
}
protected void UpdatePanel1_Load(object sender, EventArgs e)
{
string parameter = Request["__EVENTARGUMENT"];
if (parameter == "1")
{
System.Threading.Thread.Sleep(3000);
Label2.Text = DateTime.Now.ToString();
}
}
use
function refreshUpdatePanel() {
__doPostBack"<%= UpdatePanel1.ClientID %>", '1');
}
instead of
function refreshUpdatePanel() {
window.__doPostBack('UpdatePanel1', '1');
}
thank you

Categories

Resources