how to call javascript client side function from code behind file - javascript

How would I call showItems() function in aspx page from code behind.
<script>
function getItems(){
var items = [];
return items; //items=['a','b','c']
}
<form id="form1" runat="server">
<asp:Hiddenfield id="HiddenField1" runat="server"></asp:hiddenfield>
</form>
code behind:
ScriptManager.RegisterStartupScript(this, GetType(), "items", "<script type='text/javascript'>getItems()</script>", false);

A few things here...
First, you don't "call a client-side function from server-side code." What you can do is include some client-side code which itself will call the function, client-side. Which appears to be what you're doing, but I just want to make sure you understand the difference.
Second, your function is called showItems, but you're calling a function called getItems:
<script type='text/javascript'>getItems()</script>
Call showItems() instead? Like this?:
ScriptManager.RegisterStartupScript(this, GetType(), "items", "<script type='text/javascript'>showItems()</script>", false);
Third, the showItems function returns something. But you're not actually doing anything with that result. You're simply invoking the function and ignoring the result. So it's not really clear what you're trying to accomplish.

Like this:
Page.ClientScript.RegisterStartupScript(GetType(), "key", "showItems();", true);
Edit: To get the javascript return value at C# code behind Assign the values to the hidden control using the javascript code. Then you can access the Hidden control value in C# code. Take a look at this article. for example:
<script type="text/javascript">
function showItems() {
var items = new Array(3);
items[0] = "name1";
items[1] = "name2";
items[2] = "name3";
items[3] = "name4";
document.getElementById('<%=HiddenField1.ClientID%>').value = items.join(',');
}
</script>
And in the code behind:
string[] itemArr = HiddenField1.Value.Split(",".ToCharArray());

Related

Calling a Javascript in my razor page from a controller in MVC4

In my controller I have this function:
Function AppError() As ActionResult
Dim myScript As Object = "popup(" + Properties.postError + ")"
Return RedirectToAction("main", myScript)
End Function
With this function I want to call my razor page where I have a Javascript named popup whith a parameter Properties.postError.
My script is:
<script type="text/javascript">
var errMsg;
function popup(msg) {
errMsg = msg;
window.alert(errMsg);
window.window.focus();
if (window.confirm)
errmsg = '';
msg = '';
}
</script>
What I need is to popup the error message.
I follow the programm thru my debugger and I saw that it goes to my page.
But no error message window raise up.
I have already search in the web for this option without any success.
Is someone to assist me on this issue?
ADDITION - 16/2/19 12:50
what I have done so far is the following:
Function CBError() As ActionResult
Dim myScript As Object = "popup(" + Properties.postError + ")"
ViewData.Add(New KeyValuePair(Of String, Object)("ScriptName", myScript))
Return View("main", myScript)
End Function
As we can see I've change the function by addiding the ViewData
I Add a value pair arguments 1) the name 2) the value
The action of addition it works just fine and the dictionery receive it.
I my script (which is in my reazor page) I put the following:
<script type="text/javascript">
var vd = #ViewData.Item(0);
function popup(msg) {
var errMsg;
errMsg = msg;
window.alert(errMsg);
window.window.focus();
if (window.confirm)
errmsg = '';
msg = '';
//{ window.location.href = "/" }
}
</script>
When I stop (with the bebugger) in the instruction var vd = #ViewData.Item(0); I see that the ViewData is complitely empty. No values no nothing.
I also add this window.onload = #Html.Raw(ViewBag.MyScript);
And in debugger threw me an error
"Uncaught SyntaxError: Unexpected token ;"
Is there somone to instruct me why that happen?
ADDITION - 16/2/19 20:00
New version of function and Script
Function CBError() As ActionResult
Dim myScript As Object = Properties.postError
ViewData.Add(New KeyValuePair(Of String, Object)("Message", myScript))
Return View("main")
End Function<br/>
<script type="text/javascript">
$(document).ready(function (){
alert("#ViewData.Values(0)");
});
</script>
With this version I put the message value to the ViewData
But when the program comes to the point of script then all the ViwData is empty.
No Values no Keys no nothing.
It seems somewhere in the middle it lose all the data
FINAL UPDATE 17/2/19 11:13
The problem has been solved ... but not by the way we are wearing.
It was solved in an extremely simple way.
What we were asking for was to get the error message on the page we are in. From any point of the code.
So I followed the method of rendering the message to property and I read this message from the page with the following Javascript.
The function is:
Function CodePage_Error() As ActionResult
Return View("main")
End Function
End the Javascript is:
<script type="text/javascript">
$(document).ready(function () {
if ("#Properties.InnerError" !== "") {
var msg = "#Properties.InnerError";
window.alert(msg);
} else {
return false;
}
});
The Javascript is placed in the mainLayout.vbhtml file
Generally speaking, it turned out that the transfer method from the controller to the page is not possible in the MVC4 environment
You could pass the error message to the page via Viewbag, and then put the pop up script inside the document ready javascript function to check the message and display the error if required.
Controller:
public IActionResult Index()
{
ViewBag.Message = "this is your message";
return View();
}
View:
<script type="text/javascript">
$(document).ready(function (){
alert("#ViewBag.Message");
});
I think passing JS code through RedirectToAction route value parameter is not a good idea because some special characters will be encoded. You should use either ViewBag or viewmodel properties and pass the script to view in unencoded state.
Here is an example setup:
1) Use ViewBag or a viewmodel property to contain the script you want to execute in the view.
Public Function AppError() As ActionResult
' define Properties.postError here
Dim myScript As String = "popup(" + Properties.postError + ")"
ViewBag.MyScript = myScript
Return View()
End Function
2) Use an event handler e.g. window.onload assigned with #Html.Raw() from ViewBag or viewmodel property to pass unencoded function call inside <script> tag. The event handling must be placed outside function block.
<script type="text/javascript">
var errMsg;
function popup(msg) {
errMsg = msg;
window.alert(errMsg);
window.window.focus();
if (window.confirm)
errmsg = '';
msg = '';
}
// the popup will be called here
window.onload = #Html.Raw(ViewBag.MyScript)
</script>
Note that window.onload will pop up the message after the view is loaded, if you want to pop up the message in another event use any desired event handler instead (also check list of available JS DOM events).

Async Javascript callback not triggering the RaiseCallBackEvent function

In my asp.net application I used the async javascript callback.
The requirement is once the user enters the Postal code an async javascript callback function should be called. And the server side code must return me the city with respect to the postal code.
The coding I did is:
<asp:TextBox ID="txtPostCode" runat="server" CssClass="textbox" onchange="javascript: getCityAndStreet();" BorderStyle="Ridge" Height="20px" style="margin-left: 10px" Width="442px"></asp:TextBox>
This textbox onchange it will call the javascript function getCityAndStreet()
function getCityAndStreet()
{
var postalCode = document.getElementById('<%=txtPostCode.ClientID%>');
CallServer(postalCode.value, "");
}
function ReceiveCityAndStreet(rValue,context)
{
alert(rValue);
var city = document.getElementById('<%= txtCity.ClientID%>');
city.value = rValue;
}
Here the CallServer is the server side runtime javascript which is registered as below
protected void Page_Init(object sender, EventArgs e)
{
String cbReference = Page.ClientScript.GetCallbackEventReference(this, "arg", "ReceiveCityAndStreet", "context",true);
String callbackScript;
callbackScript = "function CallServer(arg, context)" + "{ " + "alert('Entered inside CallServer' + arg);" + cbReference + ";}";
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "CallServer", callbackScript, true);
}
I implemented the ICallBackHandler and by this I got 2 methods:
string ICallbackEventHandler.GetCallbackResult()
{
return cityAndStreet;
}
void ICallbackEventHandler.RaiseCallbackEvent(string eventArgument)
{
txtStreet.Enabled = true;
txtCity.Enabled = true;
cityAndStreet = eventArgument;
}
in page_load function I just disabled the txtStreet.Enabled. txtCity.Enabled text boxes and on the raise callbackevent I am enabling it.
The issue here is the RaiseCallBackEvent is not working. I mean its not been triggered implicitly.
(This application is not accessed directly in the browser it is accessed through the SharePoint site)
I think the problem is that your button actually does postback when you click on it. You do not need postback because you are calling server using AJAX. Try changing onchage handler to this:
onchange="getCityAndStreet();return false;"
This will cause your button not to trigger postback.
EDIT: Also i want to mention that you cannot change controls in RaiseCallBackEvent method. It is not an actual postback. You need to enable text fields using javascript in onSuccess method.

Call to ClientScript doesnot preserve value in Controls of Web Page

I have a small problem . If page is refreshed using F5 , TextBox should preserve its old value . In Page_Load() , if i keep // Loading(); then TextBox1 preserve its old value.
As soon as i remove comment , it loose value in TextBox1 .
Please tell me the reason behind it and What should be done to avoid it .
<script type="text/javascript">
function TextBox1_TextChanged() {
<%
Session["HitCount1"] = TextBox1.Text ;
%>
}
function getMyvalSession() {
var ff = "Loading Value";
return ff;
}
</script>
<body>
<form id="form1" runat="server">
<asp:TextBox ID="TextBox1" Name="TextBox1" runat="server"
AutoPostBack='true' onchange="TextBox1_TextChanged()"></asp:TextBox>
<%
string x = null;
x = Session["HitCount1"].ToString().Trim();
if ((x.Equals(null)) || (x.Equals("")))
{
// Session Variable is either empty or null .
}
else
{
TextBox1.Text = Session["HitCount1"].ToString();
}
%>
</form>
</body>
protected void Page_Load(object sender, EventArgs e)
{
// Loading();
}
void Loading()
{
String csname = "OnSubmitScript";
Type cstype = this.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
// Check to see if the OnSubmit statement is already registered.
if (!cs.IsOnSubmitStatementRegistered(cstype, csname))
{
string cstext = " document.getElementById(\"TextBox1\").value = getMyvalSession() ; ";
cs.RegisterOnSubmitStatement(cstype, csname, cstext);
}
}
Combining inline server-side code and code-behind code is generally a bad idea. I would recommend just using the code-behind code.
This code:
function TextBox1_TextChanged() {
<%
Session["HitCount1"] = TextBox1.Text ;
%>
}
... is not going to have the effect of the (server-side) Session entry "HitCount1" getting set to Textbox1.Text, because TextBox1_TextChanged is a client-side function, and your assignment statement is going to happen on the server side. At run time, the chunk of server code will have been removed by the compiler, so TextBox1_TextChanged will be an empty function.
The rule of thumb: Things happen on the client, or they happen on the server on postback, or they happen on the server via Ajax calls. You can't mix client and server code together.
My recommendation: switch to doing everything in code-behind. When you have it working, if you have too many postbacks, investigate Ajax calls.

JavaScript code in a tag onclick

I need to do some ugly stuff. But I cannot do it another way. what I need is
<a href='some/url/?with&params' onclick="(if confirm('Do you wanna submit?')
{some code to submit form in href property})">
but I don't know how to make inline script work... and I hesitate about the way of submitting it with window.location or document.location. Any ideas?
Try this:
on html:
Submit
<script type="text/javascript" src="myValidation.js" />
myValidation.js
I used json and javascript closures on this answer.
; //starts with this to close other js not yet closed
var MyValidation = {
actionSubmit : function() {
//your code go here
//example of calling another function
MyValidation.anotherFunction();
//example of accessing a global variable (for your validation)
MyValidation.variable;
//example of declaring local variable
var word = "hello";
//example of calling another function with parameters
MyValidation.anotherFunctionWithParameters(word, MyValidation.variable);
//the returning
return MyValidation.someValidation(word);
}
//Yes, this is a comma.
//I'm putting in the beginning so we see this and didn't forget :)
,anotherFunction : function() {
//some code
//maybe a return
}
,variable : {}
,anotherFunctionWithParameters : function(param1, param2) {
//more code, maybe a return
}
,someValidation : function(parameter) {
//some validation
return true|false;
}
};
Take a look on this:
How do JavaScript closures work?
json
Have you heard about AJAX? Google it if you don't.
The onClick parameter accepts a function name with or without parameters, not "inline scripts".
<script type=text/javascript>
function doStuff(){
if(confirm("Submit?"){
//do your stuff with AJAX to some/url/?with&params
}
}
</script>
<a href='javascript:doStuff'>link</a>

Why "this.href" does not get the href value I assigned

I am trying to get the value of the href as i need to pass a variable in query string
<a id="CA" class="CA" href='<%#"mysecondpage.aspx?ID=" + Td1.InnerText %>'
onclick="return popitup(this.href)" runat="server">comment</a>
I have to open a popup in which the "mysecondpage" should be open with a value inside a query string but this.href returns blank value and i dont know why it is not working as it worked inside itemtemplate (gridview) i have used table and filled data with angularJS repeat.
this is my popitup function:
function popitup(url) {
alert(url);
// window.open(url+id,'popup', 'width=700,height=800,scrollbars=no,resizable=no');
return false;
}
You are using a DataBinding expression <%# %>. So you have to call DataBind() in the Page_Load explicitly.
protected void Page_Load(object sender, EventArgs e)
{
DataBind();
}
If you are using Jquery,
Try this I hope it will help you
$(document).ready(function(){
$('#CA').on('click' function(event){
event.preventDefault();
var url = $(this).attr('href');
alert(url);
});
});
Get back to me if is not working

Categories