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.
Related
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>
Good day!
I need a help on activating my javascript function via on-load on code behind.
Here is my code:
string script = #"var applyCss = function () {
var css = '#CalendarPanel1-month-day-20170607, #CalendarPanel1-month-day-20170614 {background-color: #D0D3D4;}';
Ext.net.ResourceMgr.registerCssClass('someCssClassId', css);
}; ";
ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "css", script, true);
By the way, my code above works in front-end via button click.
But my desired result is, I want my javascript function to work on page load without needing to click the button. I put my javascript function in code-behind because I will put dynamic dates in the css variables. The code above still has static variables. (CalendarPanel1-month-day-20170607)
Will gladly appreaciate any response / solution. Big thanks!
You could use an immediately invoked function to do the trick. Basically you don't give a name to your javascript function and you invoke it right after it's defined.
For example:
var script = #"(function () {alert('Hello');})(); ";
ScriptManager.RegisterStartupScript(this, typeof(Page), "123", script, true);
You need to wrap the function with its body between parenthesis then another set of parenthesis to invoke the function.
You can also pass parameters to your function (which I'm assuming it's what you want to do):
var myAlertText = "Hello Hello";
var script = #"(function (myText) {alert(myText);})('" + myAlertText + "');" ;
If I were you though I would defined the function in client code and just invoke it from code behind with the right parameters.
An alternative and fancier way to call javascript code from code behind would be using X.Call(). Check out this example:
<%# Page Language="C#" %>
<!DOCTYPE html>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if (!X.IsAjaxRequest)
{
string script = #"var myJSSideVar = 'my var value';
var applyCss = function (paramOne, paramTwo) {
var css = '#CalendarPanel1-month-day-20170607, #CalendarPanel1-month-day-20170614 {background-color: #D0D3D4;}';
Ext.net.ResourceMgr.registerCssClass('someCssClassId', css);
Ext.Msg.alert('applyCss called.', 'I\'ve been run with parameters: (' + paramOne + ', ' + paramTwo + ').');
};";
var hi = "hello";
X.AddScript(script);
X.Call("applyCss", new object[] { hi, new JRawValue("myJSSideVar") });
}
}
</script>
<html>
<head runat="server">
<title></title>
</head>
<body>
<form runat="server" id="form1">
<div>
<ext:ResourceManager runat="server" />
</div>
</form>
</body>
</html>
Notice the second parameter sent to the script call is sent "raw", i.e., it calls: applyCss("hello", myJSSideVar)
If you need to pass but one single parameter you don't need to pass an array, e.g. X.Call("applyCss", hi);
I am using javascript to set asp:hiddenfield to '1' but not getting set.
I am setting it like this:
<script type="text/javascript">
function uploadComplete(sender, args) {
var myHidden = document.getElementById('<%= HdnFieldEmployeePicture.ClientID %>');
myHidden.value = '1';
}
</script>
from:
<asp:AsyncFileUpload ID="FileUpload1" OnClientUploadComplete="uploadComplete" ClientIDMode="AutoID" UploaderStyle="Modern" runat="server"/>
<asp:HiddenField ClientIDMode="Static" ID="HdnFieldHasFileUploaded" runat="server" />
I am checking it on server side:
if (HdnFieldHasFileUploaded.Value == "1")
{
but not set to 1.
AsyncControl and hidden field are inside UpdatePanel.
Your javascript code will not work because javascript method bindings get broken when your page is partially submitted using asp.net update panel. You need to add following lines of code to get it back to work.
<script type="text/javascript">
function EndRequestHandler(sender, args) {
// bind your methods here
}
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
</script>
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
I have the following script in my page:
window.onload = LoadElement;
function LoadElement() {
document.getElementsByTagName('asp:Panel');
};
function setPage(frame, page) {
document.getElementById('WindowShow').innerHTML = page;
}
At first I want the asp:Panel be read it onload. Continuing I'm calling the setPage Function in order to load a Page inside to this Panel...
But the debugger throws me the error `I can't load the porperty .innerHTML to a null reference value.
I see from the debugger that really the getElement has a value of null, but the value inside is not null.
Is someone to know what is going on here? I'm confused... very much...
ADDITIONAL INFORMATION'S
The sub to use in order to call the script is this:
Private Sub button1_Click(sender As Object, e As System.EventArgs) Handles button1.Click
Dim url As String = "/Pages/Support/Asp/Help01.aspx"
Dim urlURI As String = HttpContext.Current.Request.Url.AbsoluteUri
Dim urlPath As String = HttpContext.Current.Request.Url.AbsolutePath
Dim root_url As String = Strings.Left(urlURI, urlURI.Length - urlPath.Length)
Dim frameName As String = "WindowShow"
iPageLoad(frameName, sender, root_url + url)
End Sub
Public Sub iPageLoad(FrameId As String, sender As Object, msg As String)
Dim cstype As Type = Me.GetType()
Dim innerMess As String = msg
Dim url As String = HttpContext.Current.Request.Url.AbsoluteUri
Dim script As String = "setPage('" + FrameId + "', '" + innerMess + "')"
If Not Page.ClientScript.IsStartupScriptRegistered(Me.GetType(), "iPage") Then
Page.ClientScript.RegisterStartupScript(cstype, "iPage", script, True)
End If
End Sub
NEW SCRIPT
<td id="TD1" rowspan="9" runat="server">
<asp:Literal id="WindowShow" runat="server" Mode="PassThrough" />
<script type="text/javascript">
function setPage(page) {
document.getElementById('WindowShow');
}
</script>
</td>
With this script throw me the error ìnnerHTML is not a valid attribute for...` .
UPDATES
That is what my code has:
<table id="tbl" runat="server" class="maintable" >
<tr><td id="line1" class="tableline" runat="server">
<asp:Button ID="button1" runat="server" CssClass="tablebutton" Text="bla bla bla" />
</td>
<td id="TD1" rowspan="9" runat="server">
<asp:Literal id="WindowShow" runat="server" Mode="PassThrough" />
<script type="text/javascript">
function setPage(page) {
document.getElementById('WindowShow').innerHTML = page;
}
</script>
</td>
</tr>
</table>
And that is what is Server site look like:
<table id="MainContent_tbl" class="maintable">
<tr>
<td id="MainContent_line1" class="tableline">
<input type="submit" name="ctl00$MainContent$button1" value="bla bla bla" id="MainContent_button1" class="tablebutton" />
</td>
<td id="MainContent_TD1" rowspan="9">
'--------- It Shaw the TD1 but can't see the Literal element
<script type="text/javascript">
function setPage(page) {
document.getElementById('WindowShow').innerHTML = page;
}
</script>
</td>
</tr>
</table
Instead of asp:Panel use this:
window.onload = function () {
var panel;
panel = document.getElementById('<%=ServerSidePanel.ClientID %>');
// do something with panel
setPage(panel, "<span>Page inside panel.</span>");
};
function setPage(frame, page)
{
frame.innerHTML = page;
}
And in the code-behind expose the control in a property:
protected ServerSidePanel
{
get
{
return ... // the panel you want to get in JS
}
}
EDIT: server-side html injected panel
If you have the HTML on the server and want to have it inside the panel, there is no need to use JS at all. You can just assign it to a Literal instead of a Panel this way:
In the ASPX page:
<asp:Literal ID="injectionPoint" runat="server" CssClass="looks_like_a_panel" Mode="PassThrough" />
In the code behind (here in C#, sorry I don't speak VB):
string html;
// load somehow the html, here it is simply assigned
html = "<span>internal HTML</span>";
// assign html to literal
injectionPoint.Text = html;
That's all. No JS at all.
Here you can find a VB example doing pretty much the same, but without PassThrough mode:
Literal VB example on MSDN
Finally I found a solution to my issue which may close this question and probably opens another...
I use two scripts:
<script type="text/javascript">
window.onload = getTag()
function getTag() {
var td = document.getElementsByTagName('td');
return td;
}
</script>
<script type="text/javascript">
var myTD = getTag();
function setPage(page) {
// var ch = myTD.item(1).children[0];
//ch.value = page;
myTD.item(1).childNodes[1].innerHTML = '<iframe class="tablecolumndiv" src="' + page + '" />';
}
</script>
And my asp.net code:
<td id="TD1" rowspan="9" runat="server" class="tablecolumn">
<div id="WindowShow" runat="server" class="tablecolumndiv">
</div>
</td>
In the first script I call onload for the td element.
In the second I call the returned td from the first and passes dynamically the page I want thru an iFrame.
Now the question comes up is "Why I didn't do it from the asp.net code".
Well I did that but I was facing the problem to leave the iFrame when I finish my job.
So now... tomorrow... I'll try to close the dynamically opened iFrame and finish the all issue here...